我想把我用C# winform开发的软件卡里转换成基于MVVM模式的WPF,我才刚刚开始,还有很多问题需要解决。
其中之一是从其他窗口检索数据。
在Winform中,我使用了下面的代码,这些代码工作正常。
这是主要形式:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
string userName = string.Empty;
string userSurName = string.Empty;
string userAddress = string.Empty;
private void GetUserInfos()
{
using (var form = new UserInfosForm())
{
var dialog = form.ShowDialog();
if (dialog == DialogResult.OK)
{
this.userName = form.userName;
this.userSurName = form.userSurName;
this.userAddress = form.userAddress;
}
}
}
}
字符串
这是我想从中检索数据的表单:
public partial class UserInfosForm : Form
{
public string userName = string.Empty;
public string userSurName = string.Empty;
public string userAddress = string.Empty;
public UserInfosForm()
{
InitializeComponent();
buttonOk.DialogResult = DialogResult.OK;
buttonOk.Click += ButtonOk_Click;
}
private void ButtonOk_Click(object sender, EventArgs e)
{
userName = textBoxName.Text;
userSurName = textBoxSurName.Text;
userAddress = textBoxAddress.Text;
}
}
型
如何在WPF MVVM模式中实现该功能?
2条答案
按热度按时间kkbh8khc1#
一般来说,在WPF和MVVM中,您可以通过ViewModels来完成此操作。
假设你有
MainWindow
和MainWindowViewModel
。在主窗口上,您有一个
Button
,该命令属性绑定到MainWindowViewModel
上的OpenNewWindowCommand
。命令所做的一切,就是显示一个新的窗口,你可以在上面输入一些数据,比如上面提到的用户名等。
要显示新窗口并从新窗口中检索数据,可以使用以下代码段
字符串
当然,你需要在ViewModel中使用
Properties
而不是Fields
,ViewModel需要实现INotifyPropertyChanged
gdx19jrr2#
你应该首先学习WPF,XAML,MVVM,以实现任何事情,因为你不是在一个小任务上工作,而是在一个完整的项目上,你想移植到WPF。
任何人都可以给予一些提示,但简而言之,你需要知道,(their properties)in查看(与WinForm相同,它有代码)应在同一视图的视图模型中定义(所以,不要在后面的代码中定义它,即使像我说的那样存在,但你不会以MVVM的方式工作)最后,你需要学习如何从View Model中绑定一个XML文本到View,如果需要的话,还需要一个单一的值,类似的。
因此,在视图模型中将值定义为属性,并在同一控件中的视图中进行绑定。
字符串
但是使用像这样实现的
INotifyPropertyChanged
接口:型
你不需要点击事件来从你的文本框控件中获取值,因为如果你在XAML(你的视图)中做类似的事情,它们会自动设置。
型
最后,如果你想要整个视图,你需要这样做:
型
您将看到它是如何工作的,但这仍然是一个小任务的原始答案(让我们这样称呼它)因为你要研究整个解决方案(port it to new platform in .net environment)其中您的关键字如下- contol properties values
binding
in wpf,datacontext
,View
andView Model
(即MVVM
-模型视图视图模型模式),INotifyPropertyChanged
接口等等。