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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/771833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:16:09  来源:igfitidea点击:

How to bind to a WPF dependency property when the datacontext of the page is used for other bindings?

wpfdata-bindingdependency-properties

提问by Thomas Bratt

How to bind to a WPF dependency property when the datacontext of the page is used for other bindings? (Simple question)

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

回答by Thomas Bratt

The datacontext of the element needed to be set.

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

XAML:

XAML:

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

C#:

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); }
}

Also see this related question:

另请参阅此相关问题:

WPF DependencyProperties

WPF 依赖属性

回答by itowlson

In XAML:

在 XAML 中:

Something="{Binding SomethingElse, ElementName=SomeElement}"

In code:

在代码中:

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

Though usually you will do this the other way round and bind the UI property to the custom dependency property.

尽管通常您会反过来执行此操作并将 UI 属性绑定到自定义依赖项属性。