【发布时间】: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>
【问题讨论】: