2016-05-24 1 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

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> 
関連する問題