【问题标题】:Is it right to put a viewmodel in a resourcedictionary?将视图模型放在资源字典中是否正确?
【发布时间】:2012-01-30 08:17:29
【问题描述】:

我正在开发一个 WPF 项目,通常我使用资源字典来组织样式和颜色。当使用Expression Blend 时,它会将 viewmodel 对象放在这样的资源中:

<local:VM x:Key="VM" d:IsDataSource="True"/>

并像这样设置数据上下文

<Window.DataContext><Binding Mode="OneWay" Source="{StaticResource VM}"/></Window.DataContext>

这对于在 XAML 中使用 source 属性在这样的绑定中获取命令或属性非常有用(尤其是在数据模板中)

{Binding XXCommand,Source={StaticResource VM}}

我可以将 viewmodel 对象放在资源字典中还是最好将此视图特定于与 viewmodel 相关的每个视图中?

另外,如果我将以下样式放入资源字典中,我必须包含 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>

【问题讨论】:

    标签: wpf mvvm


    【解决方案1】:

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

    【讨论】:

    • 这是一个不错的列表,但我强烈反对作者对Option 7: DataTemplate as viewsOption 8 的看法。这些是我最常用的将 ViewModel 绑定到 View 的方法,而不是在初始启动时我使用 Option3 来显示应用程序外壳。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多