2011-06-29 35 views
4

这是列表框代码:如何从列表框中获取选定的项目在WPF中有复选框?

<ListBox x:Name="courseslistview" 
     ItemsSource="{Binding .}" 
     FontSize="18.667" 
     FontFamily="Trebuchet MS" 
     LayoutUpdated="courseslistview_LayoutUpdated"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <CheckBox Content="{Binding .}" /> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

如何使用C#来获取所有在上面的列表框中选中的复选框?

回答

14

这很可能是最好的CheckBoxListBoxItemIsSelected属性绑定,就像这样:

<DataTemplate> 
    <CheckBox Content="{Binding .}" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" /> 
</DataTemplate> 

然后你可以从ListBox.SelectedItems收集的检查/选定的项目。您还必须将SelectionMode设置为多个。

+1

非常感谢这么多codenaked – kartal

+0

我工作在WP应用程序,我得到以下错误。 在RelativeSource中找不到'AncestorType'属性,'AncestorType'无法识别或无法访问。你也可以提供Windows Phone的解决方案吗? –

+0

@BalasubramaniM - 这个问题是特定于WPF。如果以前还没有问过,我建议再问一个单独的问题。 – CodeNaked

相关问题