当页面的数据上下文用于其他绑定时,如何绑定到WPF依赖属性?

19

当页面的DataContext用于其他绑定时,如何绑定到WPF依赖属性?(简单问题)


1
当你在谷歌搜索“WPF数据绑定”时,你是不是想要寻找其他的东西? - Matt Hamilton
3
我在寻找一个有效的例子,其中页面的数据上下文已经用于其他绑定。结果发现,该元素的数据上下文需要设置为页面本身。如果需要,我会发布代码并编辑问题。 - Thomas Bratt
2个回答

34

需要设置元素的数据上下文。

XAML:

<Window x:Class="WpfDependencyPropertyTest.Window1" x:Name="mywindow">
   <StackPanel>
      <Label Content="{Binding Path=Test, ElementName=mywindow}" />
   </StackPanel>
</Window>

C#:

public static readonly DependencyProperty TestProperty =
        DependencyProperty.Register("Test",
                                    typeof(string),
                                    typeof(Window1),
                                    new FrameworkPropertyMetadata("Test"));
public string Test
{
   get { return (string)this.GetValue(Window1.TestProperty); }
   set { this.SetValue(Window1.TestProperty, value); }
}

还可以查看这个相关问题:

WPF DependencyProperties


当通过代码更改Test时,它是否会自动提供更改通知? - Kos
你是我的救星,Thomas Bratt。 - user1836155
1
我能用用户控件做到这个吗?我尝试了同样的事情,但什么也没发生... :( 也许我漏了什么.. - Jack Frost

11

在 XAML 中:

Something="{Binding SomethingElse, ElementName=SomeElement}"
在代码中:
BindingOperations.SetBinding(obj, SomeClass.SomethingProperty, new Binding {
  Path = new PropertyPath(SomeElementType.SomethingElseProperty),  /* the UI property */
  Source = SomeElement /* the UI object */
});

通常情况下,您会反过来操作并将UI属性绑定到自定义依赖属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接