将属性绑定到 Winforms 中的控件 [英] Binding property to control in Winforms

查看:42
本文介绍了将属性绑定到 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.

因此,如果我有一个属性 FirstName,我想将其绑定到文本框的 txtFirstName 文本值.因此,如果我将 FirstName 更改为值Stack",那么属性 txtFirstName.Text 也会更改为值Stack".

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".

我知道这可能听起来很愚蠢,但我会感谢您的帮助.

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# 代码片段.希望有帮助

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天全站免登陆