C# 在 XAML 中设置 <Window.DataContext>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11041976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:14:18  来源:igfitidea点击:

Setting <Window.DataContext> in XAML

c#wpfxamlmvvmdatacontext

提问by David Beck

I followed a very simple MVVM example as a basis for my program. The author had one code behind instruction he used in the main page to set the DataContext. I'm thinking I should be able to do this in the XAML instead. The MainWindowViewModel is in a directory ViewModels. The code behind works.

我遵循了一个非常简单的 MVVM 示例作为我程序的基础。作者在主页面中使用了一个代码隐藏指令来设置DataContext. 我想我应该能够在 XAML 中做到这一点。MainWindowViewModel 位于目录 ViewModels 中。背后的代码有效。

namespace RDLfromSP
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new ViewModels.MainWindowViewModel();
        }
    }
}

I can't seem to find the right combo to set it instead in the XAML

我似乎无法在 XAML 中找到正确的组合来设置它

<Window x:Class="RDLfromSP.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="300" > 

    <Window.DataContext>
        <local:ViewModels.MainWindowViewModel />
    </Window.DataContext>

Thanks in advance for your help

在此先感谢您的帮助

回答by Reed Copsey

You'll need an xml namespace mapping to the ViewModelsnamespace. Once you add that, it would be:

您将需要一个映射到ViewModels命名空间的 xml 命名空间。添加后,它将是:

<Window.DataContext>
    <vms:MainWindowViewModel />
</Window.DataContext>

(This is assuming you map vmsto the appropriate namespace.)

(这是假设您映射vms到适当的命名空间。)

This should look just like your current namespace mapping for local:, but called vms:with the appropriate namespace specified.

这应该看起来就像您当前的命名空间映射local:,但vms:使用指定的适当命名空间进行调用。