C# - 将TextBox绑定到整数

dav*_*led 16 c# data-binding winforms

如何将TextBox绑定到整数?例如,将单位绑定到textBox1.

public partial class Form1 : Form
{
    int unit;

    public Form1()
    {
        InitializeComponent();


    }

    private void Form1_Load(object sender, EventArgs e)
    {
        textBox1.DataBindings.Add("Text", unit, "???");
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 23

它需要是一个实例的公共属性; 在这种情况下,"this"就足够了:

public int Unit {get;set;}
private void Form1_Load(object sender, EventArgs e)
{
    textBox1.DataBindings.Add("Text", this, "Unit");
}
Run Code Online (Sandbox Code Playgroud)

对于双向通知,您需要UnitChanged或者INotifyPropertyChanged:

private int unit;
public event EventHandler UnitChanged; // or via the "Events" list
public int Unit {
    get {return unit;}
    set {
        if(value!=unit) {
            unit = value;
            EventHandler handler = UnitChanged;
            if(handler!=null) handler(this,EventArgs.Empty);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您不希望它在公共API上,您可以将其包装在某个隐藏类型中:

class UnitWrapper {
    public int Unit {get;set;}
}
private UnitWrapper unit = new UnitWrapper();
private void Form1_Load(object sender, EventArgs e)
{
    textBox1.DataBindings.Add("Text", unit, "Unit");
}
Run Code Online (Sandbox Code Playgroud)

有关信息,"事件列表"的内容类似于:

    private static readonly object UnitChangedKey = new object();
    public event EventHandler UnitChanged
    {
        add {Events.AddHandler(UnitChangedKey, value);}
        remove {Events.AddHandler(UnitChangedKey, value);}
    }
    ...
    EventHandler handler = (EventHandler)Events[UnitChangedKey];
    if (handler != null) handler(this, EventArgs.Empty);
Run Code Online (Sandbox Code Playgroud)


XXX*_*XXX 5

您可以使用绑定源(请参阅注释).最简单的变化是:

public partial class Form1 : Form
{
    public int Unit { get; set; }
    BindingSource form1BindingSource;

    private void Form1_Load (...)
    {
        form1BindingSource.DataSource = this;
        textBox1.DataBindings.Add ("Text", form1BindingSource, "Unit");
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您稍微分离出数据,您将获得一些概念上的清晰度:

public partial class Form1 : Form
{
    class MyData {
        public int Unit { get; set; }
    }

    MyData form1Data;
    BindingSource form1BindingSource;

    private void Form1_Load (...)
    {
        form1BindingSource.DataSource = form1Data;
        textBox1.DataBindings.Add ("Text", form1BindingSource, "Unit");
    }
}
Run Code Online (Sandbox Code Playgroud)

HTH.注意省略了访问修饰符.