[英]Bind CheckBox to SelectedItem in ListBox
我已经在WPF中创建了一个列表框,它可以执行以下操作:
它绑定到我的ViewModel中的数据源。 ListBox包含项目,每个项目旁边是一个CheckBox。 如果用户单击CheckBox,则选中该项目,然后将执行命令。 它工作正常,WPF的代码如下所示:
<ListBox ItemsSource="{Binding OCAntwort}" SelectedItem="{Binding SelectedAntwort}" >
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<!--ElementName=Window is the Name of the XAML (in root definition)-->
<CheckBox DataContext="{Binding DataContext, ElementName=Window}" Command="{Binding CheckAnswer}" CommandParameter="{Binding ElementName=cbox, Path=IsChecked}" IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem}, Path=IsSelected}" x:Name="cbox" HorizontalAlignment="Right"/>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
现在,我正在Windows Store App上尝试相同的操作,但是没有AncestorType ...如果我这样做的话:
<Style TargetType="ListBoxItem" x:Name="lbitem">
<CheckBox DataContext="{Binding DataContext, ElementName=Window}" Command="{Binding CheckAnswer}" CommandParameter="{Binding ElementName=cbox, Path=IsChecked}" IsChecked="{Binding ElementName=lbitem, Path=IsSelected}" x:Name="cbox" HorizontalAlignment="Left"/>
复选框消失,它将仅显示OCAntwort的ItemsSource。 单击一个项目将不会执行CheckBox的命令(因为没有CheckBox)。 这样做:
IsChecked="{Binding ElementName=lbitem, Path=IsSelected,RelativeSource={RelativeSource Mode=Self}}"
将显示CheckBox并执行Command,但未将其绑定到SelectedItem。
如何将CheckBox(显示在每个ListBoxItem旁边的ListBoxItem旁边)绑定到ListBox的SelectedItem? 工作代码在上方...我希望该代码在我的Windows Store应用程序中(以及以后在我的Windows Phone应用程序中)工作。
例:
您可以在此处下载示例: http : //weblogs.asp.net/marianor/archive/2008/02/04/multiselect-listview-with-checkboxes-in-wpf.aspx
这显示了我想要在Windows Store App中实现的目标。
编辑:这样做会显示具有内容和CheckBox的ListBox,但是我仍然需要通过SelectedItem绑定CheckBox。 意味着当用户单击CheckBox时,必须选择ListBoxItem,或者如果用户单击ListBoxItem,则必须选择CheckBox。
<ListBox ItemsSource="{Binding OCAntwort}" SelectedItem="{Binding SelectedAntwort}" Grid.Row="2" Grid.Column="1" x:Name="listBox" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Text}" Width="150" VerticalAlignment="Center"/>
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected, Mode=TwoWay}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
不知道您是否找到了解决方案,但是我使用以下代码在CheckBox
的IsChecked
属性和父级ListBoxItem
或ListViewItem
的IsSelected
属性之间建立了双向绑定。
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}"/>
在ListBoxItem中进行书写时,应使用TemplatedParent。
IsChecked="{Binding ElementName=lbitem,
Path=IsSelected,
RelativeSource={RelativeSource Mode=TemplatedParent}}"
我认为这可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.