简体   繁体   中英

List box Items as checkbox

I have a list box whose items are represented as check box as under

        <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>

The itemssource is assigned in the code behind

listBox1.ItemsSource = names;

The GUI displays correct number of check boxes but with no text. How can I put the "content" of the checkboxes as in my itemssource of the listbox1?

Also how can I retrieve which checkboxes the user has checked in code behind?

Add binding to Checkbox like

<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>

And when u need to get checkcbox which is checked hook Checked event in XAML like

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

code behind: in that case sender is your CheckBox private List _checked;

    private void OnChecked(object sender, RoutedEventArgs e)
          {
             _checked.Add((CheckBox)sender);
          }
private void OnUnchecked(object sender, RoutedEventArgs e)
          {
             _checked.Remove((CheckBox)sender);
          }
        <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;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM