WPF使用成熟的属性自动更新代码
程序员文章站
2022-06-08 18:41:23
...
创建一个类名为 ObservableObject的类,其中的代码如下所示:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Notepad_WPF.Helpers
{
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected PropertyChangedEventHandler PropertyChangedHandler => PropertyChanged;
public void VerifyPropertyName(string propertyName)
{
var myType = GetType();
if (!string.IsNullOrEmpty(propertyName) && myType.GetProperty(propertyName) == null)
{
var descriptor = this as ICustomTypeDescriptor;
if (descriptor != null)
{
if (descriptor.GetProperties().Cast<PropertyDescriptor>().Any(property => property.Name == propertyName))
{
return;
}
}
throw new ArgumentException("Property not found", propertyName);
}
}
public virtual void RaisePropertyChanged(string propertyName)
{
VerifyPropertyName(propertyName);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public virtual void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
{
if (PropertyChanged != null)
{
var propertyName = GetPropertyName(propertyExpression);
if (!string.IsNullOrEmpty(propertyName))
{
RaisePropertyChanged(propertyName);
}
}
}
protected static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
if (propertyExpression == null)
{
throw new ArgumentNullException("propertyExpression");
}
var body = propertyExpression.Body as MemberExpression;
if (body == null)
{
throw new ArgumentException("Invalid argument", "propertyExpression");
}
var property = body.Member as PropertyInfo;
if (property == null)
{
throw new ArgumentException("Argument is not a property", "propertyExpression");
}
return property.Name;
}
protected bool Set<T>(Expression<Func<T>> propertyExpression, ref T field, T newValue)
{
if (EqualityComparer<T>.Default.Equals(field, newValue))
{
return false;
}
field = newValue;
RaisePropertyChanged(propertyExpression);
return true;
}
protected bool Set<T>(string propertyName, ref T field, T newValue)
{
if (EqualityComparer<T>.Default.Equals(field, newValue)) { return false; }
field = newValue;
RaisePropertyChanged(propertyName);
return true;
}
protected bool Set<T>(ref T field,T newValue,[CallerMemberName] string propertyName = null)
{
return Set(propertyName, ref field, newValue);
}
}
}
可直接复制,使用方式如下所示:
上一篇: mysql 优化方案_MySQL
下一篇: 【C#】UserControl用法
推荐阅读
-
WPF中Style文件的引用——使用xaml代码或者C#代码动态加载
-
WPF中Style文件的引用——使用xaml代码或者C#代码动态加载
-
在使用shape的同时,用代码修改shape的颜色属性
-
【WPF高仿 Windows记事本】开发日记 (五) 使用成熟的自动更新代码(ObservableObject)、实现是否显示状态栏功能、鼠标的滚轮命令绑定(查看菜单功能实现)
-
C# WPF 代码编辑时 依赖项属性代码段的 快捷
-
WPF使用成熟的属性自动更新代码
-
WPF 如何在代码中使用自定义的鼠标资源
-
HTML5中meta属性的使用代码示例详解
-
PHP 保留远程文件到服务器代码管用(包括使用getid3获取音频文件属性的用法)
-
关于Java代码在应用层获取Android系统属性的使用实例