2012-05-04 66 views
-1

comboboxパターンを使用してObservableコレクションをバインドしています。comboboxにバインドできますが、今はビュー内でSelectedItemプロパティを取得する方法を探していますモデル(私は単にそれを呼び出すことはできませんパターンを制動しているので)私がそれを描写する方法は、選択された項目を指し、後で私のビューモデルで使用することができるXAMLでバインディングを作成する方法がなければならないということです。私が把握できないのはどういうことか...MVVMを使用してWPFコンボボックスのSelectedItemプロパティを取得する

私はこれをどのように達成することができますか?

XAML

<ComboBox SelectedIndex="0" DisplayMemberPath="Text" ItemsSource="{Binding Path=DocumentTypeCmb,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
      Grid.Column="1" Grid.Row="4" Margin="0,4,5,5" Height="23" 
      HorizontalAlignment="Left" Name="cmbDocumentType" VerticalAlignment="Bottom" 
      Width="230" /> 

コード

//Obesrvable collection property 
private ObservableCollection<ListHelper> documentTypeCollection = new ObservableCollection<ListHelper>(); 
public ObservableCollection<ListHelper> DocumentTypeCmb 
{ 
    get 
    { 
     return documentTypeCollection; 
    } 
    set 
    { 
     documentTypeCollection = value; 
     OnPropertyChanged("DocumentTypeCmb"); 
    } 
} 

//Extract from the method where i do the binding 
documentTypeCollection.Add(new ListHelper { Text = "Item1", IsChecked = false }); 
documentTypeCollection.Add(new ListHelper { Text = "Item2", IsChecked = false }); 
documentTypeCollection.Add(new ListHelper { Text = "Item3", IsChecked = false }); 

DocumentTypeCmb = documentTypeCollection; 

//Helper class 
public class ListHelper 
{ 
    public string Text { get; set; } 
    public bool IsChecked { get; set; } 
} 

答えて

7

はこれを試してみてください:

public ListHelper MySelectedItem { get; set; } 

とXAML:

<ComboBox ItemsSource="{Binding Path=DocumentTypeCmb,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
     SelectedItem={Binding MySelectedItem} 
     /> 

ViewModelに正しいタイプを取得/設定しているパブリックプロパティを持っているだけで、選択したアイテムをバインディングで割り当てることができます。 SelectedItemは従属性があるので、このようにバインドすることができますが、リストコントロールのSelectedItems(複数の注記)はではなく、であるため、VMにバインドすることはできません。代わりにビヘイビアを使用します。

はまた、私は私の例では、プロパティ変更通知を実装していないので、あなたは、VMから選択した項目を変更した場合、それはUIに更新されませんが、これは中に入れて自明であることに注意してください。

どう
+0

パーフェクト非常 –

+2

+1をありがとう、しかしのItemsSourceを設定するときにモード=双方向を取り除くください! - ちょうど意味をなさない。 – blindmeis

+0

@blindmeis - それは非常に真実です、私は単にOPのサンプルからその部分をコピー/ペーストしました。それはデフォルトのバインディングモードかもしれませんが、明示的に指定するのは完全に*悪い*ではありません - 少なくとも他の開発者はコードを読んで何が起こっているのか疑いがないでしょう(前のWPFコードは、新しい開発者には手がかりはなかった)。 – slugster

1

これについて?

SelectedItem={Binding SelectedDocumentType} 
4

確かに、ComboBoxSelectedItem性質を持っています。ビューモデルでプロパティを公開し、XAMLで双方向バインドを作成できます。

public ListHelper SelectedDocumentType 
{ 
    get { return _selectedDocumenType; } 
    set 
    { 
     _selectedDocumentType = value; 
     // raise property change notification 
    } 
} 
private ListHelper _selectedDocumentType; 

...

<ComboBox ItemsSource="{Binding DocumentTypeCmb, Mode=TwoWay}" 
      SelectedItem="{Binding SelectedDocumentType, Mode=TwoWay}" /> 
関連する問題