Winforms 数据绑定和验证,为什么验证失败时更新数据源? [英] Winforms databinding and validation, why is datasource updated when validation fails?
问题描述
下面的代码说明了在 winforms 中结合数据绑定和验证时的一些意外(对我来说!)行为.谁能告诉我如何在验证失败时阻止数据源更新?
The code below illustrates some unexpected (for me!) behaviour when combining data binding and validation in winforms. Can anyone tell me how I can prevent the datasource from being updated when validation fails?
非常感谢.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ValidationBug
{
/// <summary>
/// This illustrates some unexpected behaviour with winforms validation and binding
///
/// To reproduce: Run the program, enter a value into the textbox, click the X to close the form.
///
/// Expected behaviour: validation of textbox fails so data source is not updated.
///
/// Observed behaviour: data source is updated.
/// </summary>
public class Form1 : Form
{
private class Data
{
private string _field;
public string Field
{
get { return _field; }
set
{
// this should never be called, but it is.
_field = value;
}
}
}
private System.ComponentModel.IContainer components = null;
public Form1()
{
this.Load += new System.EventHandler(this.Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
AutoValidate = System.Windows.Forms.AutoValidate.EnablePreventFocusChange;
var txt = new TextBox();
// validation always fails.
txt.Validating += new CancelEventHandler((s, ev) => ev.Cancel = true);
Controls.Add(txt);
var data = new Data();
this.components = new System.ComponentModel.Container();
BindingSource bs = new BindingSource(this.components);
bs.DataSource = typeof(Data);
// only update datasource on succesful validation.
txt.DataBindings.Add(new Binding("Text", data, "Field", false, DataSourceUpdateMode.OnValidation));
}
}
}
推荐答案
我倾向于蛮力"我的代码 - 你能不能为你的 私有字符串 _field
设置一个初始值,也许在一个构造函数中?
I tend to "brute force" my code - could you set an initial value to your private string _field
, perhaps in a constructor?
此外,您确定将 CancelEventHandler
的 Cancel 属性设置为 TRUE 会将您的数据标记为无效吗?
Also, are you sure that setting your CancelEventHandler
's Cancel property to TRUE marks your data as invalid?
您甚至可能想要向您的 Data 类添加一个 private bool _valid
字段,该字段仅在有效时才返回值.
You may even want to add a private bool _valid
field to your Data class that only returns values if it is valid.
private class Data
{
private bool _valid;
private string _field;
public Data()
{
_field = null;
_valid = false;
}
public string Field
{
get
{
if (_valid)
{
return _field;
} else {
return null;
}
set
{
// this should never be called, but it is.
_field = value;
_valid = !String.IsNullOrEmpty(_field);
}
}
}
只是一些需要研究的想法.
Just some ideas to look into.
这篇关于Winforms 数据绑定和验证,为什么验证失败时更新数据源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!