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();
}
}