我是靠谱客的博主 体贴小甜瓜,这篇文章主要介绍WPF INotifyPropertyChanged类的序列化问题,现在分享给大家,希望可以做个参考。

例如,我有一个这样的类:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
[Serializable] public class CustomClass : INotifyPropertyChanged { private bool _checkbox; public int Value { get; set; } public bool Checkbox { get { return _checkbox; } set { _checkbox = value; NotifyPropertyChanged("Checkbox"); } } public int SecondValue { get; set; } public string Text { get; set; } public event PropertyChangedEventHandler PropertyChanged;  private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } }

编译它会给出一个 错误,即
公共事件 PropertyChangedEventHandler PropertyChanged;无法序列化。

为此,有必要将事件部分指定为NonSerialized,

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[Serializable] public class CustomClass : INotifyPropertyChanged { private bool _checkbox; public int Value { get; set; } public bool Checkbox { get { return _checkbox; } set { _checkbox = value; NotifyPropertyChanged("Checkbox"); } } public int SecondValue { get; set; } public string Text { get; set; } [NonSerialized] public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } }
如果我这样做,我会再次收到错误消息。
NonSerialized 不是字段类型,因此您需要将其正确指定为字段类型。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[Serializable] public class CustomClass : INotifyPropertyChanged { private bool _checkbox; public int Value { get; set; } public bool Checkbox { get { return _checkbox; } set { _checkbox = value; NotifyPropertyChanged("Checkbox"); } } public int SecondValue { get; set; } public string Text { get; set; } [field: NonSerialized] ///変更点ここ public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } }

现在您可以使用 INotifyPropertyChanged 序列化类。

最后

以上就是体贴小甜瓜最近收集整理的关于WPF INotifyPropertyChanged类的序列化问题的全部内容,更多相关WPF内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(115)

评论列表共有 0 条评论

立即
投稿
返回
顶部