2016-05-24 49 views
0

當我有我的看法組合框,並希望有一個空項目,以便能夠取消選擇的選項,我在我看來,使用此代碼:如何在CompositeCollection中使用視圖模型的屬性?

<ComboBox.Resources> 
    <CollectionViewSource x:Key="comboBoxSource" Source="{Binding ElementName=ucPrincipal, Path=DataContext.MyProperty}" /> 
</ComboBox.Resources> 
<ComboBox.ItemsSource> 
    <CompositeCollection> 
     <entities:MyType ID="-1"/> 
     <CollectionContainer Collection="{Binding Source={StaticResource comboBoxSource}}" /> 
    </CompositeCollection> 
</ComboBox.ItemsSource> 

在這種情況下,是設置ID的觀點-1表示是特殊項目。但我不太喜歡這個解決方案,因爲視圖模型取決於視圖設置正確。

所以我想有這個屬性在我的視圖模型:

public readonly MyType MyNullItem = new MyType(); 

但我不知道如何在視圖中使用它在我的複合集合中,而不是:

<entities:MyType ID="-1"/> 

這可能嗎?

謝謝。

回答

1

您需要某種綁定轉換器,它將一個列表和一個對象合併爲CompositeCollection。前一段時間,我實現與唯一的區別類似的轉換器,其轉換多個集合到一個:

/// <summary> 
/// Combines multiple collections into one CompositeCollection. This can be useful when binding to multiple item sources is needed. 
/// </summary> 
internal class MultiItemSourcesConverter : IMultiValueConverter { 
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { 
     var result = new CompositeCollection(); 

     foreach (var collection in values.OfType<IEnumerable<dynamic>>()) { 
      result.Add(new CollectionContainer { Collection = collection }); 
     } 
     return result; 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { 
     throw new NotSupportedException(); 
    } 
} 

而這種轉換器的使用看起來像這樣的XAML:

<ComboBox.ItemsSource> 
    <MultiBinding Converter="{StaticResource MultiItemSourcesConverter}"> 
     <Binding Path="FirstCollection" /> 
     <Binding Path="SecondCollection" /> 
    </MultiBinding> 
</ComboBox.ItemsSource> 
相關問題