C# - 将 TextBox 绑定(bind)到整数

标签 c# winforms data-binding

如何将 TextBox 绑定(bind)到整数?例如,将单元绑定(bind)到 textBox1。

public partial class Form1 : Form
{
    int unit;

    public Form1()
    {
        InitializeComponent();


    }

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

最佳答案

它需要是实例的公共(public)属性;在这种情况下,“this”就足够了:

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

对于双向通知,您需要 UnitChangedINotifyPropertyChanged:

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

如果您不想在公共(public) 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");
}

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

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

关于C# - 将 TextBox 绑定(bind)到整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1497489/

相关文章:

c# - 将 XML 文档转换为对象列表的 LINQ 查询导致异常

c# - 在 WebBrowser 中调用一个脚本,并等待它完成运行(同步)

java - Spring 3 在所有模型属性上错误地绑定(bind)请求数据

wpf - 将 WPF ContextMenu MenuItem 绑定(bind)到 UserControl 属性与 ViewModel 属性

c# - wa=wsignupcleanup1.0 不会在依赖方注销用户

c# - 多个独立数据库事务的并发问题?

c# - 如何在 C# windows 窗体中使用有空格的字体来创建 Excel 工作表?

c# - 使 ListBox 项目具有与项目文本不同的值

c# - 如何获取文本基线与标签水平边框之间的距离?

c# - 绑定(bind)列表框到 ObservableCollection<T> 不工作 WPF