2012-05-04 90 views
-1

我使用MVVM模式將Observable集合綁定到combobox。我可以成功綁定到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} 
     /> 

你只需要在你的視圖模型是得到的公共屬性/設置正確的類型,然後使用綁定到所選項目分配給它。注意的SelectedItem是一個依賴媒體資源相關聯,所以你可以綁定這個樣子,但是對於列表控件SelectedItems(注意是複數)是依賴項屬性,所以你不能綁定回你的虛擬機 - 這有一個簡單的解決方法改爲使用行爲。

另外請注意,我還沒有在我的例子中實現屬性更改通知,因此,如果您更改所選項目從虛擬機不會在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}" /> 
相關問題