gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:40:58 24 4
gpt4 key购买 nike

下面的代码说明了在 winforms 中组合数据绑定(bind)和验证时一些意想不到的(对我来说!)行为。谁能告诉我如何在验证失败时阻止更新数据源?

非常感谢。

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

最佳答案

我倾向于“暴力破解”我的代码 - 你能为你的 private string _field 设置一个初始值吗,或许在构造函数中?

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

您甚至可能想要将一个 private bool _valid 字段添加到您的 Data 类中,该字段仅在有效时才返回值。

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

只是一些需要研究的想法。

关于Winforms数据绑定(bind)和验证,为什么在验证失败时更新数据源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4184431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com