Problem with model view controll in Windows application
ok. I have a question about use my data model in UI. problem is with windows forms. In the presentation tier, I set my data model equals to their relevant texboxes, lables.. etc. but all the time my dat开发者_Python百科a model being change, I have to manually update the UI also. Same thing happens again when I change some value in textBox or anything else in UI, I have to update manually my data Model also.
Aren't there a way, a better way to set this to be happened automatically ? When I change data Model, UI also be changed accordingly? also When I change values in UI, data Model also be updated automatically??
Regards,
-Kushan-
You can make use of Data Binding within Windows Forms to achieve what you are going after. There are a varying number of samples here.
The sample below is a single Form
with two TextBox
(textBox1, textBox2) controls and one Button
(button1) on it. If you put a new name in textbox2 and clicked button1 it will set the property on the Person.FirstName
property which will propagate to textBox1 since it has been data bound as seen in the ctor of 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
精彩评论