当页面的datacontext用于其他绑定时,如何绑定到WPF依赖项属性?

Tho*_*att 18 data-binding wpf dependency-properties

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

Tho*_*att 33

需要设置元素的datacontext.

XAML:

<Window x:Class="WpfDependencyPropertyTest.Window1" x:Name="mywindow">
   <StackPanel>
      <Label Content="{Binding Path=Test, ElementName=mywindow}" />
   </StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

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); }
}
Run Code Online (Sandbox Code Playgroud)

另请参阅此相关问题:

WPF DependencyProperties

  • +1谢谢.最后一个易于理解,清晰的例子! (3认同)

ito*_*son 10

在XAML中:

Something="{Binding SomethingElse, ElementName=SomeElement}"
Run Code Online (Sandbox Code Playgroud)

在代码中:

BindingOperations.SetBinding(obj, SomeClass.SomethingProperty, new Binding {
  Path = new PropertyPath(SomeElementType.SomethingElseProperty),  /* the UI property */
  Source = SomeElement /* the UI object */
});
Run Code Online (Sandbox Code Playgroud)

虽然通常您会以相反的方式执行此操作,并将UI属性绑定到自定义依赖项属性.