Binding to a property from a DataModel to its parent ViewModel?
I'm using the M-V-VM pattern. I have a ViewModel and an ObservableCollection of DataModels. The list of DataModels are data-bound to a DataGrid.
When the grid is rendered, i would like one of the fields to be a ComboBox (let's say a list of string names).
This string name list is a common list that applies to all rows (i.e. DataModels).
Is there a way to bind a grid's field-level row property to the parent ViewModel?
One possible solution that i'd like to avoid is this: Have a get-property in the DataModel that essentially returns the ViewModel's property (the list of strin开发者_如何学Pythong names).
you can do it with a static resource. E.g. define your static resource in xaml
<UserControl.Resources>
<mynamespace:MyViewModel x:Key="MyViewModel" />
</UserControl.Resources>
Now you can reference this resource in your user control:
<Controls::DataGrid DataContext="{StaticResource MyViewModel}" ItemSource="{Binding MyItems}" ...
<Controls:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding MyItems, Source={StaticResource MyViewModel}" DisplayMemberPath="MyString" /> <!-- This does the job with the combo box and the strings -->
</DataTemplate>
</Controls:DataGridTemplateColumn.CellTemplate>
</Controls:DataGrid>
Hope this helps,
BR,
TJ
精彩评论