Windows应用程序中的模型视图控制器问题

时间:2010-12-08 18:43:01

标签: c# model-view-controller

确定。我有一个关于在UI中使用我的数据模型的问题。问题是Windows窗体。 在表示层,我设置我的数据模型等于他们相关的texbox,lables ..等等但是我的数据模型一直在变化,我也必须手动更新UI。当我在textBox或UI中的任何其他内容中更改某些值时,同样的事情再次发生,我还必须手动更新我的数据模型。

有没有办法,更好的方法来设置这个自动发生?当我更改数据模型时,UI也会相应更改?当我在UI中更改值时,数据模型也会自动更新??

此致

-Kushan -

1 个答案:

答案 0 :(得分:2)

您可以在Windows窗体中使用Data Binding来实现您的目标。样本数量不同here

以下示例是单个Form,其中包含两个TextBox(textBox1,textBox2)控件和一个Button(button1)。如果在textbox2中添加一个新名称并单击button1,它将在Person.FirstName属性上设置属性,该属性将传播到textBox1,因为它已被数据绑定,如Form1的ctor所示。

    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