且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

绑定到自定义的依赖项属性 - 再次

更新时间:2022-06-22 02:41:45

文本物业位于的DataContext 中的主窗口的>的不是用户控件。

The Text property is located on the DataContext of the MainWindow not of the UserControl.

因此​​,改变这一行< UC:MyUserControl1 MyTextProperty ={结合文字}/> 这个:

So change this line <uc:MyUserControl1 MyTextProperty="{Binding Text}"/> into this:

<uc:MyUserControl1 MyTextProperty="{Binding Text, ElementName=MyMainWindow}"/>

这将告诉绑定,你在谈论位于文本元素在你的主窗口。当然,由于在这个例子中我使用的ElementName ,你要去想的名称的你的窗口MyMainWindow ...

Which will tell the Binding that you're talking about the Text element located in you MainWindow. Of course, since in this example I used ElementName, you're going to want to name your window MyMainWindow...

所以添加到您的主窗口:

So add this to your MainWindow:

<Window  Name="MyMainWindow" ..... />

如果你不想命名窗口,您可以使用的RelativeSource FindAncestor这样的绑定:

If you rather not name your window, you can use the RelativeSource FindAncestor binding like this:

<wpfApplication6:MyUserControl1 MyTextProperty="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"/>

在这两种方法,你问到找到名为文本属性窗口的DataContext的。

In both ways, you are asking to find the property named 'Text' in the DataContext of the window.