gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:42:29 24 4
gpt4 key购买 nike

好的。我对在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com