Winforms数据绑定和验证,为什么在验证失败时更新数据源?

时间:2010-11-15 12:45:17

标签: winforms validation

以下代码说明了在winforms中组合数据绑定和验证时的一些意外(对我而言)行为。任何人都能告诉我如何在验证失败时阻止更新数据源吗?

非常感谢。

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));
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

我倾向于“暴力破解”我的代码 - 您是否可以在private string _field中设置初始值,可能是在构造函数中?

此外,您确定将CancelEventHandler的取消属性设置为TRUE会将您的数据标记为无效吗?

您甚至可能希望向Data类添加private bool _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);
            }
        }
    }

只需要考虑一些想法。