c# - Windows 应用程序中 Model View Controller 的问题

标签 c# model-view-controller

好的。我对在 UI 中使用我的数据模型有疑问。问题出在Windows窗体上。 在表示层中,我将我的数据模型设置为与其相关的文本框、标签等。但是我的数据模型一直在变化,我也必须手动更新 UI。当我更改 textBox 中的某些值或 UI 中的任何其他内容时,同样的事情再次发生,我还必须手动更新我的数据模型。

难道没有一种更好的方法来将其设置为自动发生吗?当我更改数据模型时,UI 是否也相应更改?另外,当我在 UI 中更改值时,数据模型也会自动更新??

问候,

-贵霜-

最佳答案

您可以使用 Data Binding在 Windows 窗体中实现你想要的。 sample 数量不等here .

下面的示例是单个 Form,上面有两个 TextBox(textBox1、textBox2)控件和一个 Button (button1)。如果您在 textbox2 中输入一个新名称并单击 button1,它将在 Person.FirstName 属性上设置属性,该属性将传播到 textBox1,因为它已被数据绑定(bind),如 Form1 的构造函数所示

    public partial class Form1 : Form
    {
        Person _person = new Person();

        public Form1()
        {
            InitializeComponent();

            textBox1.DataBindings.Add(new Binding("Text", _person, "FirstName"));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            _person.FirstName = textBox2.Text;
        }
    }

    public class Person : INotifyPropertyChanged
    {
        private String _firstName = "Aaron";
        public String FirstName
        {
            get
            {
                return _firstName;
            }
            set 
            {
                _firstName = value;
                PropertyChangedEventHandler handler = PropertyChanged;
                if(handler != null)
                    handler(this, new PropertyChangedEventArgs("FirstName"));
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }

  [1]: http://msdn.microsoft.com/en-us/library/ef2xyb33.aspx

关于c# - Windows 应用程序中 Model View Controller 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4391024/

相关文章:

c# - 找出哪个模块注册了类型

c# - 使用 SURF 匹配 OpenCV\EmguCV 中的图像

javascript - 我可以在 asp.net MVC 中实现任何 Yahoo YUI 验证框架吗?

mysql - 记录字段变化的审计历史

c# - 在 MVC 项目上覆盖 WFFM 的 succesredirect

c# - WaitForExit 实际上是在等待外部程序完成吗?

c# - 检查 C# WinForm 是否关闭

javascript - Marionette.js 与 Chaplin.js 的比较

mysql - Controller 中的 Symfony 查询

php - MVC模式上的Controller和Martin Fowler描述的Page Controller模式一样吗?