我正在开发一个WPF项目,通常我使用resourcedictionary来组织样式和颜色。使用Expression Blend时,它会将viewmodel对象放在如下资源中:
<local:VM x:Key="VM" d:IsDataSource="True"/>
并像这样设置datacontext
<Window.DataContext><Binding Mode="OneWay" Source="{StaticResource VM}"/></Window.DataContext>
这对于在XAML中使用绑定中的source
属性来获取命令或属性非常有用(特别是在datatemplate中)
{Binding XXCommand,Source={StaticResource VM}}
我可以将viewmodel对象放在resourcedictionary中,还是最好将此视图特定于与viewmodel相关的每个视图中?
另外,如果我将下面的样式放在resourcedictionary中,我必须包含viewmodel对象,
<Style x:Key="MenuItemStyle" TargetType="MenuItem">
<Setter Property="Header" Value="{Binding Desc}"/>
<Setter Property="Icon" Value="{StaticResource IconImage}" />
<Setter Property="Command" Value="{Binding ChangeShowCommand,Source={StaticResource VM}}"/>
<Setter Property="CommandParameter" Value="{Binding}"/>
</Style>