Winform 属性值绑定、转换、实时通知
单个对象绑定通知 Binding
public DemoClass MyDemo { get; set; }
public Form1()
{
InitializeComponent();
MyDemo = new DemoClass();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Binding(nameof(textBox1.Text), MyDemo, nameof(MyDemo.P_String));
}
public class DemoClass : BindableBase
{
private string _strValue;
public string P_String
{
get { return _strValue; }
set { SetProperty(ref _strValue, value); }
}
}
集合绑定通知 BindingList<T>
类似于WPF的ObservableCollection<T>
BindingList<DemoClass> DemoSource = new BindingList<DemoClass>();
listBox1.DataSource = DemoSource;
listBox1.DisplayMember = "P_String";
DemoSource.Add(new DemoClass() { P_String = DateTime.Now.ToString("ffff") });
DemoSource.RemoveAt(0);
// 集合操作
DemoSource.AddRange(list);
DemoSource.DeleteRange(list);
集合操作在ExtensionHelper
如果绑定到 GridControl,而后台修改界面上的数据,这个时候如果单个属性对象没有绑定通知,界面上是不会实时刷新的。这个时候可以在后台强制刷新。
gridControl1.BeginUpdate();
gridControl1.EndUpdate();
窗体绑定通知 BindingSource
封装窗体的数据源。可与控件(DataLayoutControl)一块应用,实现动态绑定。
添加新数据源,在数据源配置向导中,选择数据源类型(比如对象),然后选择要绑定的对象即可。
bindingSource1.DataSource = demoObj;
扩展
扩展类
using System.Windows.Forms;
static class BindingExtend
{
/// <summary>
/// 控件绑定数据源
/// </summary>
/// <param name="control">控件</param>
/// <param name="propertyName">控件属性名称</param>
/// <param name="dataSource">数据源对象</param>
/// <param name="dataMember">绑定属性名称</param>
public static void Binding(this Control control, string propertyName, object dataSource, string dataMember)
{
if (control.DataBindings[propertyName] != null)
{
control.DataBindings.Remove(control.DataBindings[propertyName]);
}
Binding b = new Binding(propertyName, dataSource, dataMember, false, DataSourceUpdateMode.OnValidation, null);
control.DataBindings.Add(b);
}
}
属性更新类
using System.ComponentModel;
using System.Windows.Forms;
/// <summary>
/// 线程安全的属性通知更新类
/// </summary>
public class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void SetProperty<T>(ref T propertyValue, T newValue, [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
{
if (Equals(propertyValue, newValue))
{
return;
}
propertyValue = newValue;
OnPropertyChanged(propertyName);
}
private void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
{
var form = Application.OpenForms[0];
if (form != null && form.IsHandleCreated)
{
// 保证线程安全
form.Invoke(new Action(() =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}));
}
}
}