[英]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.