Click here to Skip to main content
15,880,543 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
XML
<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
C#
public partial class MainWindow : Window
    {        
        CompanyViewModel CompVM; //this is my viewmodel       
        public MainWindow()
        {
            InitializeComponent();
            CompVM = (CompanyViewModel)base.DataContext;
        }
}


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
Posted
Comments
Rob Philpott 30-May-14 4:48am    
Why not in code just do DataContext = new CompanyViewModel() ?
steviesama 17-Jun-15 23:55pm    
Doing that in code will temporarily alleviate the problem, but if say you are doing that in a UserControl to circumvent the problem, if you instantiate that user control in another window, that object reference not set will bubble up to that window.
kida atlantis 1-Jun-14 22:43pm    
Thanks a lot

1 solution

Base.DataContext is not required
you can simply use
CompVM = (CompanyViewModel)this.DataContext;
 
Share this answer
 
Comments
kida atlantis 16-Jun-14 1:40am    
thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900