user433023
user433023

Reputation: 267

Why is the DataContext null in the Loaded Event?

I am using Activator.Createinstance to create an object. There're two scenarios in which I create an object. One when the object is created in the default state without caring about functionality. Second when it has some properties/data to load, which I read from XML file. I read an xml file and create a specific object based on the content in that file and then call a method of that object to load the properties. The problem occurs when the user control loads: The datacontext is null most of the times but not always. This doesn't happen when I create the object with no data to be loaded.

Following code initializes the object:

Type gadgetType = Type.GetType(ObName);
IControl ctrl = (IControl)Activator.CreateInstance(gadgetType);

This code executes in both scenarios. The only additional code which executes in second case is following.

ctrl.CreateFromXml(item);//item is xelement

and in Control the loaded event goes like this.

 void Control_Loaded(object sender, RoutedEventArgs e)
    { ControlViewModel cvm = (ControlViewModel)this.DataContext; //DataContext is null }

Upvotes: 0

Views: 1357

Answers (1)

sixth_way
sixth_way

Reputation: 41

For anyone else having this issue, you can access the DataContext in code-behind on initialization by handling the DataContextChanged event instead of the Loaded event. In my experience, the DataContext has usually been null in the Loaded event.

In the constructor:

DataContextChanged += new DependencyPropertyChangedEventHandler(OnDataContextChanged);

Event handler:

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    // your data context won't be null here.  At least it 
    // wasn't for me.
    if (DataContext is not null)
    {
        // your stuff here
    }
}

Upvotes: 0

Related Questions