WPF - How to read values from checkbox items that

2019-09-14 05:11发布

问题:

I am building an app that will return data from database based on the items that are checked on check box. I have successfully displayed data from database by binding the data. Like this:

XAML:

<ListBox x:Name="listBox1" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="52" Margin="141,264,0,0" VerticalAlignment="Top" Width="307" SelectionMode="Multiple">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox x:Name="checkBox1" IsChecked="{Binding IsSelected}"  Content="{Binding NacinGrejanja}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

C#:

       private void Window_Loaded_1(object sender, RoutedEventArgs e)
    {
        Dataset1 ds= new Dataset1 ();
        GrejanjeTableAdapter gta = new GrejanjeTableAdapter();
        gta.Fill(ds.Grejanje);
        listbox1.DataContext = ds.Grejanje;
    }

But I am unable to figure out how to extract string values from checked values and then again search for those values in database. I can't access any of the properties for checkBox1 through code.

Also I would want first to check if any of the checkbox items is checked in the first place.

回答1:

You can use following linq:

ds.Grejanje.Where(item => item.IsSelected == true);

It will return the list of items which are checked.