wpf 将几个复选框的 ischecked 绑定到静态列表

wpf binding several checkboxes' ischecked to static list

这是对我发布的问题第二部分的重述,理解将两个问题放在一个条目中并不好,这里是:

我正在使用 foreach 循环以编程方式创建多个复选框并将它们添加到名为 myStackPanel 的 StackPanel 中。我可以将其更改为任何其他类型的构造(例如数组):

foreach (something)
{
    CheckBox newCheckBox = new CheckBox();
    myStackPanel.Children.Add(newcheckBox);
}

此外,还有一个非静态 class myClass 和一个静态 属性 myStaticList:

public class myClass
{
    public static ObservableCollection<bool> myStaticList { get; set; }
}

我想将动态创建的复选框的 isChecked 绑定到 myStaticList。我不知道该怎么做。

请帮忙! TIA

如果你想绑定 IsChecked 属性,那么你可以在后面的代码中这样做:

        for (int i = 0; i < myClass.myStaticList.Count; i++)
        {
            CheckBox newCheckBox = new CheckBox();

            Binding binding = new Binding();
            binding.Path = new PropertyPath(string.Format("[{0}]", i));
            binding.Source = myClass.myStaticList;
            BindingOperations.SetBinding(newCheckBox, CheckBox.IsCheckedProperty, binding);

            myStackPanel.Children.Add(newCheckBox);
        }

更新:

另一种解决方案是在 XAML 中处理此问题:

    <ItemsControl x:Name="myStackPanel" 
                  ItemsSource="{Binding Source={x:Static local:myClass.myStaticList}}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Vertical"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <CheckBox IsChecked="{Binding Path=., Mode=OneWay}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

在此解决方案中,您可以将 ItemTemplate 预定义为 CheckBox 并像这样动态添加 bool 数据,而不是创建动态 CheckBoxes

foreach(something)
{
    myClass.myStaticList.Add(true or false);
}

注意myStaticList必须在myClass的静态构造函数中实例化:

public class myClass
{
    public static ObservableCollection<bool> myStaticList { get; set; }

    static myClass()
    {
        myStaticList = new ObservableCollection<bool>();
    }
}