C# DevExpress TextEdit组件EditValueChanged事件判断触发事件来源
版本1
通过设置断点,找到 EventArgs 参数是ChangingEventArgs类型:
ChangingEventArgs 类有两个重要的属性:
- IsTextChanging:用户输入文本内容触发的EditValueChanged事件
- IsBoundUpdatingEditValue:给TextEdit绑定数据源时触发的EditValueChanged事件
但是很可惜,这两个属性是内部方法,我们要通过.NET反射获取属性的值,参考下面代码:
C# 全选
private void txtOrg1_EditValueChanged(object sender, EventArgs e)
{
if (this.IsAddOrEditMode && e is DevExpress.XtraEditors.Controls.ChangingEventArgs ev)
{
//IsTextChanging:输入文本内容触发
//IsBoundUpdatingEditValue:绑定数据源时触发的EditValueChanged事件
var value = (Boolean)ObjectHelper.GetPropertyValue(ev, "IsBoundUpdatingEditValue");
//IsBoundUpdatingEditValue=false,输入文本内容触发
if (value == false && !txtOrg2.EditValue.IsEmpty())
{
this.SetEditorBindingValue(txtOrg1, txtOrg1.EditValue);
this.SetEditorBindingValue(txtOrg2, "", true);
}
}
}
版本2
因为有多个地方需要判断,我们把判断逻辑封装起来,重构后代码:
C# 全选
private void txtOrg1_EditValueChanged(object sender, EventArgs e)
{
if (this.IsAddOrEditMode && e.IsUserChangingValue())
{
if (!txtOrg2.EditValue.IsEmpty())
{
this.SetEditorBindingValue(txtOrg1, txtOrg1.EditValue);
this.SetEditorBindingValue(txtOrg2, "", true);
}
}
}
EventExtensions.cs
C# 全选
/// <summary>
/// 事件扩展类
/// </summary>
public static partial class EventExtensions
{
/// <summary>
/// 判断TextEdit.EditValueChanged事件是否用户修改值触发
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public static bool IsUserChangingValue(this EventArgs e)
{
var type = e.GetType();
if (type.FullName == "DevExpress.XtraEditors.Controls.ChangingEventArgs")
{
//IsTextChanging:输入文本内容触发
//IsBoundUpdatingEditValue:绑定数据源时触发的EditValueChanged事件
var p1 = type.GetProperty("IsTextChanging", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var p2 = type.GetProperty("IsBoundUpdatingEditValue", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var IsTextChanging = (bool)p1.GetValue(e, null);
var IsBoundUpdatingEditValue = (bool)p2.GetValue(e, null);
return IsTextChanging || IsBoundUpdatingEditValue == false;
}
else
{
return false;
}
}
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
CSFrameworkV6 C/S框架网