![](/img/trans.png)
[英]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.