[英]How to get Selected items in WPF CheckBox ListBox
使用列表框項目中的復選框,如何從列表中獲取選定的復選框
<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中引發異常
private void btnSelected(object sender, RoutedEventArgs e)
{
foreach (ListBoxItem item in listBox1.Items)
{
if (item.ToString() == "true")
{
MessageBox.Show(item.Content.ToString());
}
}
}
您可以將這些項目中的每一個的數據上下文從UI移開,並創建對象的ObservableCollection
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中
<ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=Selected}"
Content={Binding Path=Description}" />
</DataTemplate>
</ItemTemplate>
您選擇的項目現在可以在ObservableCollection中使用,而不是遍歷UI元素
有這樣的模板
<ListBox.ItemTemplate>
<DataTemplate>
........
<CheckBox Content=""
IsChecked="{Binding IsSelected, Mode=TwoWay,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ListViewItem}}}" />
..........
<!-- Use Other UIElements to Show your Data -->
那么上面的綁定將與模型同步isSelected和列表視圖選擇兩種方式,然后在代碼中使用SelectedItems。
For Each s As myPoco In myListView1.SelectedItems
' do something here with
Next
我建議這段代碼:
private void save_Click(object sender, RoutedEventArgs e)
{
foreach (CheckBox item in list1.Items)
{
if (item.IsChecked)
{
MessageBox.Show(item.Content.ToString());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.