自定义控件及数据绑定的问题。

angloy 2016-11-21 09:59:38
我为了实现TextBox的一些附加功能,自定义了一个控件,控件里面放置了一个TexBox控件,并自定义了一个属性TextValue。目的是通过绑定TextValue属性并且能够显示在Textbox中。目前绑定的功能能够实现没有问题,但是出现了一个问题就是当自定义控件失去焦点时,哪怕没有更改TextBox中的值也会触发绑定类中的PropertyChanged事件。这让我非常头疼,这样我就没办法在业务逻辑中判断绑定类中的属性是否发生了更改从而进行业务逻辑的判断了。我希望的是只有当属性TextValue的值发生变更时才触发绑定类中的PropertyChanged事件。
下面是我的代码片段,望各位大神指点一二。

自定义控件代码如下:

public partial class UDoubleInputBox : UserControl
{
private string _textValue;
private string _regexString;
private int _fieldDigit = 0;
private int _defaultValue = 0;

public int FieldDigit
{
get
{
return _fieldDigit;
}
set
{
_fieldDigit = value;
_regexString = @"^([0-9]\d*\.\d{0," + _fieldDigit.ToString() + @"}$)|^([0-9]\d*)$";
}
}
public int DefaultValue
{
get { return _defaultValue; }
set { _defaultValue = value; }
}
public string TextValue
{
get
{
//一旦控件失去焦点后,不管TextValue值有没有发生变化,都会执行这段代码
return _textValue;
}
set
{
if (_textValue == null ||
_textValue != value)
{
textBox1.Text = value;
}
}
}
public UDoubleInputBox()
{
InitializeComponent();
FieldDigit = 0;
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == string.Empty)
{
textBox1.Text = DefaultValue.ToString();
_textValue = DefaultValue.ToString();
return;
}

Match m = Regex.Match(textBox1.Text, _regexString);

if (!m.Success)
{
int selectionStart = textBox1.SelectionStart;
textBox1.Text = _textValue;
textBox1.SelectionStart = selectionStart;
}
else
{
_textValue = textBox1.Text;
}
}
}

绑定的类的代码片段如下:

public class ProductBaseInfo:INotifyPropertyChanged
{
private decimal productNetWeight;
[Display(Name = "产品净重")]
[Required]
[PlaceHolder(Name = "单个产品的重量")]
public Decimal ProductNetWeight{
get{
return productNetWeight;
}
set{
//一旦控件失去焦点后,不管TextValue值有没有发生变化,都会执行这段代码
productNetWeight = value;
NotifyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyChanged([CallerMemberName] string propertyName=null)
{
if (null != PropertyChanged)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

类和控件的绑定代码如下:
#region 绑定产品单重
uDoubleInputBox2.DataBindings.Add("TextValue", CostAccounting.WorkBlankProduct_SysCostAccounting,
"ProductNetWeight", true, DataSourceUpdateMode.OnPropertyChanged, null);
#endregion
...全文
110 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧