Winform数据绑定基类

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;


public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private readonly SynchronizationContext _syncContext;
private readonly TaskScheduler _uiTaskScheduler;
public BindableBase()
{
_syncContext = WindowsFormsSynchronizationContext.Current;
_uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
}

protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(storage, value))
{
return false;
}

storage = value;
RaisePropertyChanged(propertyName);
return true;
}

protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(storage, value))
{
return false;
}

storage = value;
onChanged?.Invoke();
RaisePropertyChanged(propertyName);
return true;
}

protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
//PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(propertyName)));
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}

protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
{
//if (PropertyChanged != null)
//{
// _syncContext.Post(new SendOrPostCallback(_ =>
// {
// PropertyChanged(this, args);
// }), null);
//}

Task.Factory.StartNew(() =>
{
PropertyChanged(this, args);
}, CancellationToken.None, TaskCreationOptions.None, _uiTaskScheduler);
//this.PropertyChanged?.Invoke(this, args);
}
}
***************************************************使用方法**************************************************

直接继承基类,在属性Set中使用RaisePropertyChanged事件

posted @   懒树懒  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示