Reputation: 283
I want to know how you would bind a View specific data type to your View from a ViewModel.
To be more concrete I have a ContextMenu as part of a DatagridView. Now I can bind the ItemSource of my ContextMenu to either a List of MenuItems or a List of Strings (<= implementing a Converter on this).
Both options work fine, but I want to know which is the best and why. I am asking cause I have read that I should try to not use the System.Windows.* Namespace in my ViewModel, and when I Bind a List of MenuItems of course I use this Namespace but on the other Hand if I bind strings and just convert it... This feels weird.
SampleCode (using Caliburn):
<DataGrid x:Name="OverviewItems">
<DataGrid.ContextMenu>
<ContextMenu ItemsSource="{Binding AllColumns, Converter={StaticResource String_Menu_Converter}}" >
<!-- Alternative: <ContextMenu ItemsSource="{Binding AllColumns}" >-->
<ContextMenu.ItemContainerStyle>
<Style>
<Setter Property="cal:Message.Attach" Value="[Event Click]=[SetVisibilityExecute($_clickeditem)]" />
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
Upvotes: 0
Views: 325
Reputation: 69985
In WPF, we manipulate data object, not UI objects. So it is true that you should not have any UI objects in your view model. The correct way to get around this issue is to manipulate data objects in the view model that we can then data bind with the UI controls that we declare in DataTemplate
s. So in your case, you could have a collection of custom objects that have a property to bind to the MenuItem.Header
property and another to bind to the MenuItem.Command
property for example:
<DataTemplate DataType="{x:Type YourPrefix:YourCustomType}">
<MenuItem Header="{Binding Header}" Command="{Binding Command}" />
</DataTemplate>
...
<Menu ItemsSource="{Binding YourCustomTypeCollection}" />
Upvotes: 2