WPF依赖项属性 [英] WPF DependencyProperties

查看:86
本文介绍了WPF依赖项属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚意识到我一直在强制绑定/依赖属性,但并没有真正从根本上理解这个概念。

I have just realized I've been coercing binding/dependency properties and not really fundamentally understanding the concept.

这里是依赖属性:

public string Problem
{
    get { return (string)GetValue(ProblemProperty); }
    set { SetValue(ProblemProperty, value); }
}

public static readonly DependencyProperty ProblemProperty =
    DependencyProperty.Register(
    "Problem",
    typeof(string),
    typeof(TextBox));

XAML是这样的:

<TextBlock Text="{Binding Path=Problem}"/>

我正在手动设置问题属性设置为对象的构造函数中的值,但不会相应地更新 TextBlock 。 。 。有任何想法吗?我在绑定上尝试了 Mode = OneWay Mode = TwoWay ,但仍然没有

I'm manually setting the Problem property to a value in the constructor of the object but it doesn't update the TextBlock accordingly . . . any ideas? I've tried Mode="OneWay" and Mode="TwoWay" on the binding and it still doesn't work.

我认为这应该可以自动工作吗?还是我从根本上犯错了?

I thought this was supposed to work automatically? Or am i fundamentally getting something wrong?

谢谢

推荐答案

您拥有的问题肯定与您的DataContext有关。 {Binding}扩展名需要知道您绑定到的属性的位置。它查看的默认位置是元素DataContext,默认情况下始终将其设置为其父元素的DataContext。如果将DataContext沿逻辑树移动到父窗口,则DataContext将为null(因为窗口的DataContext为null)。因此,您在文本块上的{Binding}表示将我的Text属性绑定到我的DataContext的问题问题上……这是空的。

The problem your having is definitely related to your DataContext. The {Binding} extension needs to know where the property lives that you are binding to. The default location it looks at is the elements DataContext which by default is always set to the DataContext of it's parent element. If you walk the DataContext up the logical tree to the parent window, The DataContext would be null (because the DataContext of your window is null). Therefore your {Binding} on your textblock is saying "Bind my Text property to the Problem roperty of my DataContext...which is null.

有几种方法一个解决方案就是像Jobi提到的那样,并设置要绑定的Element属性,使其指向定义DependencyProperty的Window,如下所示:

There are a couple of ways to solve this. One would be to do just like Jobi mentioned and set the Element property of you binding to point to the Window where the DependencyProperty is defined like this:

<TextBlock Text="{Binding Path=Problem,ElementName=_window}" />

另一种选择是将窗口的DataContext设置为指向自身,这样,其内容中包含的所有元素都将具有窗口的DataContext。

Another option would be to set the DataContext of your Window to point to itself. That way all the elements contained in it's content will all have the DataContext of the window.

<Window ....
        DataContext="{Binding RelativeSource={RelativeSource Self}}">

现在,无论何时您需要绑定到窗口中定义的属性(例如您的问题依赖属性),都可以这样做:

Now anytime you need to binding to properties defined in the window (like your Problem dependency property), then you can just do this:

<TextBlock Text="{Binding Problem}" />

这篇关于WPF依赖项属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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