[英]WPF User Control Dependency Property not working when bound to a ViewModel property
[英]Dependency Property on a user control not updating the property when bound data changes
我看到其他人有時會遇到此問題,最好的是,我可以告訴我重復了幾個修復程序的變體,但尚未使它起作用。
我知道綁定的數據正在發送適當的INotify事件,因為我可以將其他控件綁定到文本塊之類的數據,並隨着對象屬性的更改看到其內容更改,但是我的用戶控件似乎根本沒有收到該事件。
public partial class MappingSelector : UserControl
{
public Type OutputDriver
{
get { return (Type)GetValue(OutputDriverProperty); }
set { Console.WriteLine(value.ToString()); SetValue(OutputDriverProperty, value); UpdateUI(); }
}
// Using a DependencyProperty as the backing store for OutPutDriver. This enables animation, styling, binding, etc...
public static readonly DependencyProperty OutputDriverProperty =
DependencyProperty.Register("OutputDriver", typeof(Type), typeof(MappingSelector), new PropertyMetadata(null));
public MappingSelector()
{
InitializeComponent();
(this.Content as FrameworkElement).DataContext = this;
//UpdateUI();
}
}
該安裝程序具有一個永遠不會觸發的控制台跟蹤,因此我相信不會設置該屬性。
然后,我使用以下方法綁定到它:
<root:MappingSelector OutputDriver="{Binding LoadedProfile.UsedDriverInterface, ElementName=page, UpdateSourceTrigger=PropertyChanged}"/>
而且我知道LoadedProfile.UsedDriverInterface
正在更新並發送適當的事件,因為我也有它可以正常工作:
<TextBlock Text="{Binding LoadedProfile.UsedDriverInterface, ElementName=page, UpdateSourceTrigger=PropertyChanged}"/>
后期編輯:這可行,但這真的是我需要做的嗎? 有沒有更好的辦法? 將此添加到用戶控件構造函數;
var OutputDriverDPD = DependencyPropertyDescriptor.FromProperty(OutputDriverProperty, typeof(MappingSelector));
OutputDriverDPD.AddValueChanged(this, (sender, args) =>
{
OutputDriver = (Type)GetValue(OutputDriverProperty);
});
該安裝程序具有一個永遠不會觸發的控制台跟蹤,因此我相信不會設置該屬性。
這是一個陷阱。 您定義的屬性獲取器和設置器是為了您的方便。 WPF框架不會調用它們,它將直接使用依賴項屬性。 永遠不要在需要完成的那些獲取和設置過程中做任何事情。
如果要對屬性更改做出反應,請使用已經發現的回調。 您的控制台跟蹤應該在其中,而不是在setter中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.