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

自闭症网瘾萝莉.ら 提交于 2019-12-03 04:22:53

问题


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


回答1:


The datacontext of the element needed to be set.

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

Also see this related question:

WPF DependencyProperties




回答2:


In 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.



来源:https://stackoverflow.com/questions/771833/how-to-bind-to-a-wpf-dependency-property-when-the-datacontext-of-the-page-is-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!