K
K
KirillMB2014-12-01 18:15:01
WPF
KirillMB, 2014-12-01 18:15:01

How to make a dynamic CheckBox list in WPF?

Good evening.
There is a list List<KeyValuePair<di, string>> _regionsList;in it id and the name of the region is stored.
How to display this data in a ListBox as a CheckBox with Content the name of the region?
And how to make it so that you can put N checkmarks.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sumor, 2014-12-01
@KirillMB

In the simplest case, it should look something like this:
XAML:

<ListBox x:Name="lst">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Value}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

In code, for example:
lst.ItemsSource = new List<KeyValuePair<int, string>>()
{
    new KeyValuePair<int, string>(1, "1"),
    new KeyValuePair<int, string>(2, "2"),
};

This code will show you your list with checkboxes. You can attach a change event to the checkbox and catch which element is checked or unchecked.
If desired, you can get a list of marked ones, but this is not so trivial.
It is better to use an object that has a boolean property, such as IsChecked, for display, and bind it to the IsChecked CheckBox.
For example:
Class:
class MyClass
{
    public int id { get; set; }
    public string Name { get; set; }
    public bool IsChecked { get; set; }
}

XAML:
<ListBox x:Name="lst">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Adding elements:
lst.ItemsSource = new List<MyClass>()
{
    new MyClass(){id=1, Name="1"},
    new MyClass(){id=2, Name="2"},
};

In this case, the check mark by the user is immediately reflected in the linked list, and you can easily get a list of checked ones:
foreach(var tObj in (lst.ItemsSource as List<MyClass>).Where(myObj => myObj.IsChecked))
    MessageBox.Show(tObj.Name);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question