列表框项目作为复选框

时间:2015-03-16 08:47:10

标签: c# xaml

我有一个列表框,其项目表示为

下的复选框
        <ListBox Height="237" HorizontalAlignment="Center" Name="listBox1" VerticalAlignment="Top" Width="150" Margin="0,10,0,0" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox>
                    </CheckBox>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

itemssource在

后面的代码中分配
listBox1.ItemsSource = names;

GUI显示正确数量的复选框但没有文本。我怎样才能把&#34;内容&#34;如我在listbox1的itemssource中的复选框?

另外,我如何检索用户在代码后面检查了哪些复选框?

2 个答案:

答案 0 :(得分:3)

向Checkbox添加绑定,如

<ListBox Height="237" HorizontalAlignment="Center" Name="listBox1" VerticalAlignment="Top" Width="150" Margin="0,10,0,0" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content={Binding}>
                    </CheckBox>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

当你需要获得在XAML中检查钩子Checked事件的checkcbox时

                <DataTemplate>
                    <CheckBox Content={Binding} Checked="OnChecked" Unchecked="OnUnchecked">
                    </CheckBox>
                </DataTemplate>

代码背后:在这种情况下,发件人是您的CheckBox 私人列表_checked;

    private void OnChecked(object sender, RoutedEventArgs e)
          {
             _checked.Add((CheckBox)sender);
          }
private void OnUnchecked(object sender, RoutedEventArgs e)
          {
             _checked.Remove((CheckBox)sender);
          }

答案 1 :(得分:1)

        <ListBox.ItemTemplate>
            <DataTemplate DataType="ListBoxItem">
               <CheckBox Content="{Binding name}" IsChecked="{Binding isChecked}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>

public MainWindow()
    {
        InitializeComponent();
        List<MyListBoxItem> names = new List<MyListBoxItem>();
        names.Add(new MyListBoxItem("salim", true));
        listBox1.ItemsSource = names;
    }

    void getCheckedNames()
    {
        for (int i = 0; i < listBox1.Items.Count; i++)
        {
            if (((MyListBoxItem)listBox1.Items[i]).isChecked)
            {
                // Do things..
            }
        }
    }

    class MyListBoxItem
    {
        public string name { get; set; }
        public bool isChecked { get; set; }

        public MyListBoxItem(string name, bool isChecked)
        {
            this.name = name;
            this.isChecked = isChecked;
        }
    }