1
切換什麼是最好的/優雅到ItemsControl.ItemsSource結合不同最好在一個給定的財產的來源呢?如何2個數據源之間的ListBox.ItemsSource
該綁定應該只對2個集合中的一個進行,ItemControl綁定到的集合的選擇應該基於某個屬性。
我有一個視圖綁定到ViewModel。 我想要綁定的集合位於該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 2013-05-08 14:25:54
@Rachel我希望只能綁定到這2個集合中的一個,我希望能夠選擇它的集合 – makc 2013-05-08 14:28:05
在這種情況下, 'DataTrigger'在這裏可能更合適,因爲它會在條件改變時正確地重新評估'ItemsSource'屬性。 – Rachel 2013-05-08 14:40:54