Подтвердить что ты не робот

Как привязать свойство зависимости WPF, когда datacontext страницы используется для других привязок?

Как связать с свойством зависимости WPF, когда datacontext страницы используется для других привязок? (Простой вопрос)

4b9b3361

Ответ 1

Должен быть установлен datacontext элемента.

XAML:

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

С#:

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

Ответ 2

В 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 */
});

Хотя обычно вы будете делать это наоборот и привяжите свойство пользовательского интерфейса к свойству пользовательской зависимости.