1

ItemsControl.ItemsSource を特定のプロパティで最適な2 つの異なるソースにバインドするための最良のエレガントな方法は何ですか?

バインドは 2 つのコレクションの 1 つにのみ行う必要があります。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();
    }
}
4

1 に答える 1

5

別の値に基づいDataTriggerてバインディングを変更したいので、ここではおそらくA の方が適切でしょう。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トリガーされた値が変更されるたびに、コンバーターは正しく再評価されます

于 2013-05-09T11:50:02.133 に答える