选择/取消选中XAML中“CheckListBox”中的所有复选框
问题描述:
我搜索了这个主题并找到了几个讨论。 我不喜欢那些实现是他们要么隐含特殊的绑定数据(与IsSelected属性)或缺乏正常的键盘支持。选择/取消选中XAML中“CheckListBox”中的所有复选框
列表中的复选框更多的是装饰性的东西,而不是功能性的扩展,因此应该对其进行相应的处理。
我从这个好的和有用的文章开始:http://www.gbogea.com/2010/01/02/mvvm-multiselect-listbox
但我beleive赞成视图模型的黑客查看不太好做法。它的ViewModel适用于视图和模型。当然,恕我直言。
因此,我改变一点点,这个XAML完成:
<ListBox Name="checkboxList"
ItemsSource="{Binding Sports}"
Margin="0,5"
SelectionMode="Multiple">
<ListBox.ItemContainerStyle>
<Style>
<Setter Property="ListBoxItem.Background" Value="Transparent"/>
<Setter Property="ListBoxItem.Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="Bd"
SnapsToDevicePixels="true"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}, Path=IsSelected, Mode=TwoWay}"
Content="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这里选中复选框处于同步与ListBoxItem.IsSelected和列表框不知道绑定数据特殊性。
这是好的。 但是有什么办法通过添加一个复选框到控件模板来为ListBox添加Select | Deselect All?仅使用XAML。
答
你可以使用例如Interactivity
从Blend SDK
<ListBox ItemsSource="{Binding Data}" SelectionMode="Extended">
<ListBox.Template>
<ControlTemplate TargetType="ListBox">
<StackPanel>
<CheckBox Content="All">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Checked">
<is:CallMethodAction MethodName="SelectAll"
TargetObject="{Binding RelativeSource={RelativeSource TemplatedParent}}" />
</i:EventTrigger>
<i:EventTrigger EventName="Unchecked">
<is:CallMethodAction MethodName="UnselectAll"
TargetObject="{Binding RelativeSource={RelativeSource TemplatedParent}}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</CheckBox>
<ItemsPresenter />
</StackPanel>
</ControlTemplate>
</ListBox.Template>
</ListBox>
做这样的事情不过,这并没有解决一个问题,你没有提到或想到的,即该CheckBox
的状态时不会改变选择被改变而不使用它。您可以使用MultiBinding
和值转换器将IsChecked
状态绑定到正确的状态,然后您也可以删除事件。这也是相当混乱。
问题是? – vulkanino 2012-02-21 14:06:56
呃..忘了问题=)对不起。 – 2012-02-21 14:13:40