简体   繁体   English

环境<window.datacontext>在 XAML 中</window.datacontext>

[英]Setting <Window.DataContext> in XAML

I followed a very simple MVVM example as a basis for my program.我遵循了一个非常简单的 MVVM 示例作为我的程序的基础。 The author had one code behind instruction he used in the main page to set the DataContext .作者有一个代码隐藏指令,他在主页中使用它来设置DataContext I'm thinking I should be able to do this in the XAML instead.我想我应该能够在 XAML 中执行此操作。 The MainWindowViewModel is in a directory ViewModels. MainWindowViewModel 位于 ViewModels 目录中。 The code behind works.背后的代码有效。

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在此先感谢您的帮助

You'll need an xml namespace mapping to the ViewModels namespace.您需要一个映射到ViewModels命名空间的 xml 命名空间。 Once you add that, it would be:添加后,它将是:

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

(This is assuming you map vms to 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:并指定了适当的命名空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM