如何在 WPF CheckBox ListBox 中获取所选项目 [英] How to get Selected items in WPF CheckBox ListBox
本文介绍了如何在 WPF CheckBox ListBox 中获取所选项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Am 使用列表框项中的复选框,如何从列表中获取选中的复选框
Am Using the checkbox in listbox items, how to get the selected checkboxes from the list
<ListBox ItemsSource="{Binding NameList}" HorizontalAlignment="Left" Margin="16,68,0,12" Name="listBox1" Width="156" IsEnabled="True" SelectionMode="Multiple" Focusable="True" IsHitTestVisible="True" IsTextSearchEnabled="False" FontSize="12" Padding="5" SelectionChanged="listBox1_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Content="{Binding Path=CNames}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我试图遍历 listboxitems 中的选定项目,但它在 listboxitem 中抛出异常
I tried to loop thru the selected items in the listboxitems, but it throws exception in listboxitem
private void btnSelected(object sender, RoutedEventArgs e)
{
foreach (ListBoxItem item in listBox1.Items)
{
if (item.ToString() == "true")
{
MessageBox.Show(item.Content.ToString());
}
}
}
推荐答案
您可以将每个项目的数据上下文从 UI 移开,并创建一个 ObservableCollection 对象
You could move the data context for each of these items away from the UI and create an ObservableCollection of objects
public ObservableCollection<CheckedItem> List { get;set;}
public class CheckedItem : INotifyPropertyChanged
{
private bool selected;
private string description;
public bool Selected
{
get { return selected; }
set
{
selected = value;
OnPropertyChanged("Selected");
}
}
public string Description
{
get { return description; }
set
{
description = value;
OnPropertyChanged("Description");
}
}
/* INotifyPropertyChanged implementation */
}
然后在你的 ListBox ItemTemplate
Then in your ListBox ItemTemplate
<ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=Selected}"
Content={Binding Path=Description}" />
</DataTemplate>
</ItemTemplate>
您选择的项目现在在 ObservableCollection 中可用,而不是在 UI 元素中循环
Your selected items are now available in the ObservableCollection rather than looping through UI elements
这篇关于如何在 WPF CheckBox ListBox 中获取所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文