在Resources中分配和使用WPF DataContext的正确方法

时间:2013-05-06 12:42:58

标签: wpf xaml mvvm

我的应用需要打开一个UserControl,需要parameter/property来包含一年。 对于今年,我将让我的控件显示一些编辑值。

我遇到的问题是,我声明的Window.Resource部分有contextmenu我正在接近Gridview。从资源中的contextmenu开始,我无法直接绑定到Commands上的ViewModel

我通过在我的ViewModel中添加StaticResource作为Xaml来解决了这个问题。不幸的是,这会导致我的xaml生成我的ViewModel,而且我无法传递我的参数或属性'year',当我检索我的数据时,它会在年份= 0时完成。

有没有办法替换我为我的contextmenu提供的viewmodel绑定,以便它可以访问我在代码中设置的viewmodel?

<UserControl.Resources>
    <vm:ViewModel x:Key="viewModel" />

    <ribbon:ContextMenu x:Key="MyContextMenu"
                         x:Shared="False"
                         Placement="MousePoint" >
        <ribbon:Menu Focusable="false">
            <ribbon:Button 
                Command="{Binding Source={StaticResource viewModel}, Path=MyCommand}"
                Label="MyLabel"/>
        </ribbon:Menu>
    </ribbon:ContextMenu>

</UserControl.Resources>

1 个答案:

答案 0 :(得分:3)

是的,这是可能的。您可以创建一个包含DataContext的虚拟类:

public class Proxy:DependencyObject
{
    public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(Proxy));
    public object Data 
    {
        get { return this.GetValue(DataProperty); }
        set { this.SetValue(DataProperty, value); }
    }
}

在资源中引用它并将DataContext绑定到其Data-property:

<UserControl.Resources>
    <local:Proxy x:Key="proxy" Data="{Binding}"/>
</UserControl.Resources>

现在,Data Property保存了您的ViewModel,您可以像这样绑定它:

<ribbon:ContextMenu x:Key="MyContextMenu"
                     x:Shared="False"
                     Placement="MousePoint" >
    <ribbon:Menu Focusable="false">
        <ribbon:Button 
            Command="{Binding Source={StaticResource proxy}, Path=Data.MyCommand}"
            Label="MyLabel"/>
    </ribbon:Menu>
</ribbon:ContextMenu>