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

mak*_*akc 1 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}}" />
Run Code Online (Sandbox Code Playgroud)

转换器:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Rac*_*hel 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>
Run Code Online (Sandbox Code Playgroud)

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