如何在ListBox.ItemsSource的2个数据源之间切换

时间:2013-05-08 14:23:01

标签: wpf binding itemscontrol multibinding

将ItemsControl.ItemsSource最好地绑定到 2 不同来源的最佳/优雅方法是什么?

绑定只应该对2个集合中的一个进行,ItemsControl绑定到的集合的选择应该基于某些属性。

我有一个绑定到ViewModel的View。 我想要绑定的集合位于该ViewModel下的不同层次结构路径中。

我有一个基于MultiBinding的解决方案,但我认为应该有更优雅的解决方案。

<CollectionViewSource x:Key="CVS">
      <CollectionViewSource.Source  >
          <MultiBinding Converter="{StaticResource myMultiBindingConverter}">
              <Binding  Path="XXXX.YYYY.ObservableCollection1"  />
              <Binding Path="XXXX.ObservableCollection2" />                    
          </MultiBinding>
      </CollectionViewSource.Source>                            
</CollectionViewSource>

<ListBox  x:Name="myListBox"                                   
          ItemsSource="{Binding Source={StaticResource CVS}}" />

转换器:

public class myMultiBindingConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {

        foreach (var item in values)
        {
            if(myDependecyProperty == getFirstCollection)
            {
              //make sure the item is of first collection type based on its item property
              return item;
             }
            else
            {
              //make sure the item is of the second collection type
              return item;
            }

        }
        return null;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter,
        System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

1 个答案:

答案 0 :(得分:5)

此处DataTrigger可能更合适,因为您要根据其他值更改ItemsSource绑定

<Style x:Key="MyListBoxStyle" TargetType="ListBox">
    <Setter Property="ItemsSource" Value="{Binding XXX.ObservableCollection2}" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding SomeValue}" Value="SecondCollection">
            <Setter Property="ItemsSource" Value="{Binding XXX.YYY.ObservableCollection2}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

与转换器不同,只要触发值发生变化,DataTrigger就会被正确地重新评估