将viewmodel放在resourcedictionary中是正确的吗?

时间:2012-01-30 08:17:29

标签: wpf mvvm

我正在开发一个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>

1 个答案:

答案 0 :(得分:0)

这可能就是答案:MVVM Instantiation Approaches。很好地解释了几种实例化方法。