【发布时间】:2013-05-08 14:23:00
【问题描述】:
在给定属性上最好将 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();
}
}
【问题讨论】:
-
为什么不让
ViewModel包含一个组合两个集合的属性?毕竟,它应该对视图进行建模:) -
@Rachel 我只想绑定到这两个集合中的一个,条件是我希望能够选择它是哪个集合
-
在这种情况下,
DataTrigger在这里可能更合适,因为它会在您的条件发生变化时正确地重新评估ItemsSource属性。 -
@Rachel DataTrigger 是添加它作为答案的正确方法,我会接受它
-
当然,它已被添加为答案:)
标签: wpf binding itemscontrol multibinding