WPF 依赖属性不起作用
我有一个自定义依赖属性,如下定义:
public static readonly DependencyProperty MyDependencyProperty =
DependencyProperty.Register(
"MyCustomProperty", typeof(string), typeof(MyClass));
private string _myProperty;
public string MyCustomProperty
{
get { return (string)GetValue(MyDependencyProperty); }
set
{
SetValue(MyDependencyProperty, value);
}
}
现在我尝试在 XAML 中设置该属性,
<controls:TargetCatalogControl MyCustomProperty="Boo" />
但是 DependencyObject 中的 setter 永远不会被命中!尽管当我将属性更改为常规属性而不是 Dep Prop 时确实如此
I have a custom Dependency Property defined like so:
public static readonly DependencyProperty MyDependencyProperty =
DependencyProperty.Register(
"MyCustomProperty", typeof(string), typeof(MyClass));
private string _myProperty;
public string MyCustomProperty
{
get { return (string)GetValue(MyDependencyProperty); }
set
{
SetValue(MyDependencyProperty, value);
}
}
Now I try set that property in XAML
<controls:TargetCatalogControl MyCustomProperty="Boo" />
But the setter in DependencyObject never gets hit! Although it does when I change the property to be a regular property and not a Dep Prop
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个..
Try this..
除非您手动调用它,否则不会。您可以将一个属性更改处理程序添加到 DependancyProperty 构造函数调用中,以便在属性更改时收到通知。
调用此构造函数:
http://msdn.microsoft.com/en-us/library /ms597502.aspx
使用此构造函数创建的 PropertyMetadata 实例:
http: //msdn.microsoft.com/en-us/library/ms557327.aspx
编辑:此外,您没有正确实现依赖属性。您的
get
和set
应分别使用GetValue
和SetValue
,并且您不应该有类成员来存储价值。 DP 的成员名称也应该是{PropertyName}Property
,例如MyCustomPropertyProperty
如果get
/set
和注册的属性名称是MyCustomProperty
。请参阅 http://msdn.microsoft.com/en-us/library/ms753358。 aspx 了解更多信息。希望有帮助。
It doesn't, unless you call it manually. There's a property-changed handler you can add to the DependancyProperty constructor call to be notified of when the property changes.
Call this constructor:
http://msdn.microsoft.com/en-us/library/ms597502.aspx
With a PropertyMetadata instance created by this constructor:
http://msdn.microsoft.com/en-us/library/ms557327.aspx
EDIT: Also, you are not implementing the dependancy property correctly. Your
get
andset
should useGetValue
andSetValue
respectively, and you should not have a class member to store the value. The member name of the DP should also be{PropertyName}Property
, e.g.MyCustomPropertyProperty
if theget
/set
and property name as registered isMyCustomProperty
. See http://msdn.microsoft.com/en-us/library/ms753358.aspx for more information.Hope that helps.
也许您正在使用 MVVM,并覆盖 View 的 DataContext ?
如果这样做,则更改 MyCustomProperty 的事件将在原始 DataContext 上引发,而不是在新 ViewModel 上引发。
Maybe you are using MVVM, and overriding the DataContext of your View ?
If you do, then the event for changing MyCustomProperty will be raised on the original DataContext and not on the new ViewModel.