当复选框值更改时,更改WPF组合框上的数据绑定

问题描述:

我有一个WPF组合框,它是一个集合的数据绑定,但根据不同的复选框被选中或不是我想改变哪个集合组合框绑定到。当复选框值更改时,更改WPF组合框上的数据绑定

基本问题是我有一个MyCustomer的大集合,我也有一个MyCustomer的过滤集合 - 过滤是相当密集的,我不想用集合视图做它的主要原因是它已经是过滤后的集合已经存在 - 因此需要简单地切换组合的数据绑定。

我希望得到一个纯粹的XAML解决方案,显然写一些代码将是一个相对简单的解决方案,但它不觉得它应该是必需的。

下面是一个使用DataTrigger切换集合的例子:

<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:sys="clr-namespace:System;assembly=mscorlib" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <StackPanel.Resources> 
     <x:Array x:Key="notes" Type="{x:Type sys:String}"> 
      <sys:String>do</sys:String> 
      <sys:String>re</sys:String> 
      <sys:String>mi</sys:String> 
     </x:Array> 
     <x:Array x:Key="letters" Type="{x:Type sys:Char}"> 
      <sys:Char>a</sys:Char> 
      <sys:Char>b</sys:Char> 
      <sys:Char>c</sys:Char> 
     </x:Array> 
    </StackPanel.Resources> 

    <CheckBox x:Name="chkLetters" Content="Use Letters"/> 
    <ListBox> 
     <ListBox.Style> 
      <Style TargetType="{x:Type ListBox}"> 
       <Setter Property="ItemsSource" Value="{StaticResource notes}"/> 
       <Style.Triggers> 
        <DataTrigger Binding="{Binding IsChecked, ElementName=chkLetters}" Value="True"> 
         <Setter Property="ItemsSource" Value="{StaticResource letters}"/> 
        </DataTrigger> 
       </Style.Triggers> 
      </Style> 
     </ListBox.Style> 
    </ListBox> 
</StackPanel> 

对于你来说这些不会是不同的数组,但可能与过滤器或其他东西不同的CollectionViewSources,但原理是一样的。

我知道的最好方法是使用一些内部'获取'正确集合的shell集合。

所以你有你的UnfilteredCollection和你的FilteredCollection,然后是一个名为BindingCollection的属性,它在其“getter”中评估一些状态(复选框将被绑定到这个状态)以确定要检索哪个集合。

如果使用MVVM的UI和藏品之间的数据绑定,一个办法做到这一点会是这样:

<!-- Your ComboBox binds to some shell collection --> 
<ComboBox ItemsSource="{Binding BindingCollection}" /> 
<!-- The input to this item will determine which collection is internally exposed --> 
<CheckBox IsChecked="{Binding UseFilteredSet}" /> 

,然后让视图模型(中间层)的文件做这样的事情(我不包括INotifyPropertyChanged的实施细节,但我可以,如果你愿意的话):

private ObservableCollection<MyCustomer> UnfilteredCollection 
{ 
    get { return _unfilteredCollection; } 
} 

private ObservableCollection<MyCustomer> FilteredCollection 
{ 
    get { return _filteredCollection; } 
} 

// The public collection to which your ComboBox is bound 
public ObservableCollection<MyCustomer> BindingCollection 
{ 
    get 
    { 
     return UseFilteredSet ? 
      FilteredCollection : 
      UnfilteredCollection; 
    } 
} 

// CheckBox is bound to this state value, which tells the bindings on the shell 
// collection to refresh when the value of this state changes. 
public bool UseFilteredSet 
{ 
    get { return _useFilteredSet; } 
    set 
    { 
     _useFilteredSet = value; 
     OnPropertyChanged("UseFilteredSet"); 
     OnPropertyChanged("BindingCollection"); 
    } 
} 
+0

谢谢KP - 昨天我有这个想法,但希望有一个'纯粹的'xaml解决方案 - 也许我在咆哮错误的树和一个纯粹的xaml解决方案不是正确的方式去在第一个事情地点。 – Scott 2009-03-05 00:23:31