WPF 用户控件的 DataContext 为 Null [英] WPF User Control's DataContext is Null

查看:44
本文介绍了WPF 用户控件的 DataContext 为 Null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户控件,其中控件的 XAML 可以像平常一样绑定到来自父级数据上下文的适当属性(数据上下文在 xaml 中传播).

I have a user control where the XAML of the control can bind to the appropriate properties from the parent's data context like normal (the data context propagates in xaml).

例如,我有一个窗口,例如我将其 DataContext 设置为 ObjectA.我在窗口中的用户控件然后尝试访问 dataContext 中的属性

For example, I have a window whose DataContext I am setting to ObjectA for example. My user control within the window is then try to access the properties within the dataContext

所以我的窗口的 xaml 和后面的代码都可以看到一个非空的 DataContext.

So my window's xaml and code behind can both see a non-null DataContext.

DataContext 传播到的控件可以在 Xaml 中看到非空 DataContext,但在后面的代码中看不到.

My control that DataContext propagates to can see a non-null DataContext in the Xaml but not in the code behind.

处理这个问题的正确方法是什么?

What is the proper way of handling this?

推荐答案

如果你需要检查 DataContext 是否正在设置你可以使用 DataContextChanged

failing that if you need to check whether the DataContext is being set you can use 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
    }
}

注意它不会进入 UserControl1_DataContextChanged,直到 DataContext 从 null 更改为不同的值.

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

不确定这是否能回答您的问题,但在调试问题时非常方便.

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

这篇关于WPF 用户控件的 DataContext 为 Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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