绑定属性来控制的WinForms [英] Binding property to control in Winforms

查看:187
本文介绍了绑定属性来控制的WinForms的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,当属性值发生变化时,它控制的绑定属性改变什么是一个属性绑定到一个控制的最佳途径。

What is the best way to bind a property to a control so that when the property value is changed, the control's bound property changes with it.

所以,如果我有一个属性我要绑定到一个文本框的 txtFirstName 文本值。所以,如果我改变价值堆栈,那么属性 txtFirstName.Text 也变成值堆栈。

So if I have a property FirstName which I want to bind to a textbox's txtFirstName text value. So if I change FirstName to value "Stack" then the property txtFirstName.Text also changes to value "Stack".

我知道这听起​​来可能愚蠢的问题,但我会AP preciate的帮助。

I know this may sound a stupid question but I'll appreciate the help.

推荐答案

您必须实施 INotifyPropertyChanged的键,添加绑定到文本框。

You must implement INotifyPropertyChanged And add binding to textbox.

我公司将提供C#code片段。希望它能帮助

I will provide C# code snippet. Hope it helps

class Sample : INotifyPropertyChanged
{
    private string firstName;
    public string FirstName
    {
        get { return firstName; }
        set
        {
            firstName = value;
            InvokePropertyChanged(new PropertyChangedEventArgs("FirstName"));
        }
    }

    #region Implementation of INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    public void InvokePropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, e);
    }

    #endregion
}

用法:

 Sample sourceObject = new Sample();
 textbox.DataBindings.Add("Text",sourceObject,"FirstName");
 sourceObject.FirstName = "Stack"; 

这篇关于绑定属性来控制的WinForms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆