在代码中指定DataContext

时间:2011-10-24 13:26:38

标签: wpf xaml datacontext

我有一个简单的视图,我想绑定到我的ViewModel。我目前正在使用Source =格式进行数据绑定,但是希望将其转换为在代码中指定DataContext。

这就是我所拥有的,它正在发挥作用......

XAML:

   <Window.Resources>
        <local:ViewModel x:Key="ViewModel" />
    </Window.Resources>

    <Button Content="Click">
        <local:EventToCommand.Collection>
            <local:EventToCommandCollection>
                <local:EventToCommand Event="Click" Command="{Binding Source={StaticResource ViewModel}, Path=ClickCommand, diag:PresentationTraceSources.TraceLevel=High}" />
                <local:EventToCommand Event="GotFocus" Command="{Binding Source={StaticResource ViewModel}, Path=GotFocusCommand}" />
            </local:EventToCommandCollection>
        </local:EventToCommand.Collection>
    </Button>
</Window>

ViewModel代码:

public class ViewModel
{
    public Command ClickCommand { get; set; }
    public Command GotFocusCommand { get; set; }

    public ViewModel()
    {
        ClickCommand = new Command((obj) => { Execute(obj); return null; });
        GotFocusCommand = new Command((obj) => { Execute(obj); return null; });
    }

    void Execute(object param)
    {
        if (param != null)
            System.Windows.MessageBox.Show(param.ToString());
        else
            System.Windows.MessageBox.Show("Execute");
    }
}

现在,我想要做的就是在我的Window代码背后:

public MainWindow()
{
    InitializeComponent();

    DataContext = new ViewModel();
}

并删除XAML中的Window.Resources部分,但我无法弄清楚应如何相应地更改我的Binding字符串。

1 个答案:

答案 0 :(得分:2)

DataContext是默认Source,因此这应该有效:

<local:EventToCommand Event="GotFocus" Command="{Binding GotFocusCommand}" />