[ACCEPTED]-WPF User Control's DataContext is Null-wpf-controls

Accepted answer
Score: 27

failing that if you need to check whether 6 the DataContext is being set you can use 5 the DataContextChanged

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();

        DataContextChanged += new DependencyPropertyChangedEventHandler(UserControl1_DataContextChanged);
    }

    void UserControl1_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        // You can also validate the data going into the DataContext using the event args
    }
}

Note it wont enter 4 UserControl1_DataContextChanged until DataContext 3 is changed from null to a different value.

Not 2 sure if this answers your question but can 1 be quite handy to use in debugging issues.

Score: 14

I think you are checking the 'DataContext' in 6 the constructor of the UserControl. It will 5 be null at the Constructor since the user 4 control hasnt yet created while execution 3 is in the constructor code. But check the 2 property at Loaded event you will see the 1 object properly.

public partial class UserControl1
{
    public UserControl1()
    {
        this.InitializeComponent();

        //DataContext will be null here 
        this.Loaded += new RoutedEventHandler(UserControl1_Loaded);
    }

    void UserControl1_Loaded(object sender, RoutedEventArgs e)
    {
        //Check DataContext Property here - Value is not null
    }
}
Score: 14

I would check to see whether you are having 4 a binding error at runtime. Add this namespace 3 to your XAML:

xmlns:debug="clr-namespace:System.Diagnostics;assembly=System"

and check the debugger's Output 2 window for relevant error messages.

Alternatively, can 1 you show us more code?

More Related questions