Freitag, 30. Juli 2010

Silverlight: DataGrid and Comboxbox with MVVM

If you are using a MVVM pattern with a view model you have generally the problem to bind a combobox inside a Datagrid because you cannot access the data context of your view by referencing with the elementname syntax. The trick to bind your Comboxbox inside a DataGridTemplateColumn is to define the reference to your viewmodel with a StaticResoucre and use this for the DataContext-Binding and combobox-Binding:

StaticResoucre of the viewmodel
   1:  
   2:     <controls:ChildWindow.Resources>
   3:         <ViewModels:SettingsViewModel x:Key="SettingsViewModel" />
   4:     </controls:ChildWindow.Resources>
Binding the view to your viewmodel
   1: <Grid x:Name="LayoutRoot" Margin="2" DataContext="{StaticResource SettingsViewModel}">
Combobox-Binding in the Datagrid
   1: <sdk:DataGridTemplateColumn.CellEditingTemplate>
   2:     <DataTemplate>
   3:         <ComboBox ItemsSource="{Binding Gesellschaften,Source={StaticResource SettingsViewModel}}" 
   4:                   DisplayMemberPath="Name" SelectedValue="{Binding GesellschaftId, Mode=TwoWay}" 
   5:                   SelectedValuePath="GesellschaftId"  />
   6:     </DataTemplate>
   7: </sdk:DataGridTemplateColumn.CellEditingTemplate>

Keine Kommentare:

Kommentar veröffentlichen