c# – 未附加PropertyChanged
我在
WPF中有一个可视化控件,它利用了依赖属性.这些属性由字段支持,这些字段是类,有时需要在实际修改包含的类时通知所有绑定,更改属性值.
简单地说: > MyDepProp的类型为MyClass; MSDN说,当首次使用依赖属性时,PropertyChanged附加到DependencyObject.它在Visual Studio 2010中有效.但是,在安装Visual Studio 2012后,它停止工作:即使使用了DP(例如绑定附加到它),PropertyChanged也为null,我无法通知任何人更改. 我仍然使用Visual Studio 2010编译工具包,所以看起来,这是一个破坏框架的问题,它与VS 2012一起更新. 我是否正确使用PropertyChanged事件?或者它是VS 2012更新的.NET 4.0框架中的错误?有谁遇到过类似的问题? 编辑:一段有缺陷的代码: public partial class MyImageControl : INotifyPropertyChanged,IHandle<ImageRefresh> { // *************************** // *** Dependency property *** // *************************** private void OnDataSourceChanged() { // ... } private static void DataSourceChanged(DependencyObject d,DependencyPropertyChangedEventArgs e) { if (d is MyImageControl) ((MyImageControl)d).OnDataSourceChanged(); } public static readonly DependencyProperty DataSourceProperty = DependencyProperty.Register("DataSource",typeof(IDataSource),typeof(MyImageControl),new PropertyMetadata(null,DataSourceChanged)); public IDataSource DataSource { get { return (IDataSource)GetValue(DataSourceProperty); } set { SetCurrentValue(DataSourceProperty,value); if (PropertyChanged != null) PropertyChanged(this,new PropertyChangedEventArgs("DataSource")); } } // *********************************** // *** INotifyPropertyChanged impl *** // *********************************** public event PropertyChangedEventHandler PropertyChanged; // ************************************* // *** Method,which exposes the bug *** // ************************************* public void Handle(ImageRefresh message) { if (PropertyChanged != null) PropertyChanged(this,new PropertyChangedEventArgs("BackgroundKind")); if (PropertyChanged != null) PropertyChanged(this,new PropertyChangedEventArgs("DataSource")); } } 供参考,IHandle接口: public interface IBaseHandle { } public interface IHandle<TMessage> : IBaseHandle { void Handle(TMessage message); } 场景: >使用Binding将DataSource绑定到另一个属性 解决方法
首先,这段代码是多余的:
if (PropertyChanged != null) PropertyChanged(this,new PropertyChangedEventArgs("DataSource")); 建议不要在通常的属性设置器中编写任何其他代码,因为WPF DP系统直接访问DP而不使用setter或getter. 其次,您的控件继承了DependencyObject,允许您添加Dependecny属性. UPDATE 我认为像你一样设置CurrentValue会导致细微的错误.通常由于某些内部原因应该更改值时使用SetCurrentValue().例如.当用户键入文本时,TextBox使用SetCurrentValue()设置其Text属性值.这允许保存绑定. 根据你在评论中所说的,你可以尝试: >将值设置为null然后返回.>为DataSource实现INotifyPropertyChanged>调用DependencyObject.InvalidateProperty() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |