[英]XAML binding not working on dependency property?
我正在嘗試(但失敗)對 xaml 中的依賴屬性進行數據綁定。 當我在后面使用代碼時它工作得很好,但不是在 xaml 中。
用戶控件只是一個綁定到依賴屬性的TextBlock
:
<UserControl x:Class="WpfTest.MyControl" [...]>
<TextBlock Text="{Binding Test}" />
</UserControl>
依賴屬性是一個簡單的字符串:
public static readonly DependencyProperty TestProperty
= DependencyProperty.Register("Test", typeof(string), typeof(MyControl), new PropertyMetadata("DEFAULT"));
public string Test
{
get { return (string)GetValue(TestProperty); }
set { SetValue(TestProperty, value); }
}
我有一個常規屬性,在主窗口中通常實現INotifyPropertyChanged
。
private string _myText = "default";
public string MyText
{
get { return _myText; }
set { _myText = value; NotifyPropertyChanged(); }
}
到現在為止還挺好。 如果我將此屬性綁定到主窗口上的TextBlock
,則一切正常。 如果MyText
發生變化並且一切正常,則文本會正確更新。
<TextBlock Text="{Binding MyText}" />
但是,如果我在我的用戶控件上做同樣的事情,什么也不會發生。
<local:MyControl x:Name="TheControl" Test="{Binding MyText}" />
現在有趣的部分是,如果我在它背后的代碼中做同樣的綁定工作!
TheControl.SetBinding(MyControl.TestProperty, new Binding
{
Source = DataContext,
Path = new PropertyPath("MyText"),
Mode = BindingMode.TwoWay
});
為什么它在 xaml 中不起作用?
依賴屬性聲明必須如下所示:
public static readonly DependencyProperty TestProperty =
DependencyProperty.Register(
nameof(Test),
typeof(string),
typeof(MyControl),
new PropertyMetadata("DEFAULT"));
public string Test
{
get { return (string)GetValue(TestProperty); }
set { SetValue(TestProperty, value); }
}
UserControl 的 XAML 中的綁定必須將控件實例設置為源對象,例如通過設置 Bindings 的RelativeSource
屬性:
<UserControl x:Class="WpfTest.MyControl" ...>
<TextBlock Text="{Binding Test,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</UserControl>
同樣非常重要的是,永遠不要在其構造函數中設置 UserControl 的DataContext
。 我確定有類似的東西
DataContext = this;
刪除它,因為它有效地阻止了從 UserConrol 的父級繼承 DataContext。
通過在后面的代碼中的 Binding 中設置Source = DataContext
顯式設置綁定源,而在
<local:MyControl Test="{Binding MyText}" />
綁定源隱式是當前 DataContext。 但是,該 DataContext 已通過 UserControl 的構造函數中對 UserControl 本身的賦值設置,而不是從窗口繼承的 DataContext(即視圖模型實例)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.