如何以正确的方式在Wpf MVVM模式中定义数据上下文 [英] How to define datacontext in Wpf MVVM pattern in proper way

查看:191
本文介绍了如何以正确的方式在Wpf MVVM模式中定义数据上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有谁知道如何在xaml或后面的代码中为viewmodel定义datacontext.
下面是我尝试过的代码,然后在Windows.DataContext下的xaml中出现错误,因为对象引用未设置为对象的实例".

在xaml中这样定义

Hi ,

can any know how to define datacontext for viewmodel in xaml or code behind .
below is the code i tried then am getting error as" Object reference not set to an instance of an object" in xaml under windows.DataContext.

In xaml defined like this

<Window x:Class="Demo.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:local="clr-namespace:Demo.ViewModel"

        Title="Demo" Height="768" Width="1024" Loaded="OnWindowsLoaded" ResizeMode="NoResize"  WindowStartupLocation="CenterScreen">
    <Window.DataContext>
        <local:CompanyViewModel/> //here am getting object reference not set error.
    </Window.DataContext>
</Window>



在后面的代码中



In code behind

public partial class MainWindow : Window
    {        
        CompanyViewModel CompVM; //this is my viewmodel       
        public MainWindow()
        {
            InitializeComponent();
            CompVM = (CompanyViewModel)base.DataContext;
        }
}



它没有问题,但为什么会出现此错误却无法解决.任何人都可以告诉我上面代码中的错误是什么.

是实现MVVM模式的新手.



Its working with no issues but why am getting this error couldnt get it. can any one tell me what was mistake made in the above code.

am newbie in Implementing MVVM pattern

推荐答案

Base.DataContext不需要
您可以简单地使用
CompVM =(CompanyViewModel)this.DataContext;
Base.DataContext is not required
you can simply use
CompVM = (CompanyViewModel)this.DataContext;


这篇关于如何以正确的方式在Wpf MVVM模式中定义数据上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆