[英]How can I display the selected data from a ComboBox from one window to another with WPF and MVVM?
我在学习WPF和MVVM这两个概念的道路上处于起步阶段。 我目前正在开发一个名为:测验应用程序的应用程序。 基本上,我希望用户在第一个窗口中写下他们的名字并选择测验中问题的难度级别。
第一个窗口看起来像这样:
我接下来要做的是,当用户写下他的名字并选择难度级别时,下一步按钮将打开另一个窗口,在其中显示以下消息:
欢迎,'他的名字'! 您为测验选择了“简单/中等/困难”级别!
我搜索了很多教程,但没有找到任何东西。 他们中的大多数人在同一个窗口中显示了两条消息,但我想在新窗口中显示它们。
你能帮助我吗?
非常感谢!
为了打开新窗口,您必须创建其类的实例(因此您必须调用构造函数)。
另一方面,您在欢迎屏幕中拥有所有数据,因此我建议您执行以下操作:
// Constructor of next window
public NextWindow(string name, string level)
{
// If you are using MVVM, you want DataContext to hold data, so
// you most probably create your Datacontext here
var vm = new NextWindowViewModel();
// So you need to define appropriate properties in you ViewModel
vm.Name = name;
vm.Level = level;
DataContext = vm;
}
我会这样处理它:
Main View Model
,它将有一个名为Current View Model
的属性,它的类型要么是基本视图模型,要么是可观察对象,或者你现在孩子们叫它什么。User Control
(您当前的视图)。Login View Model
。Main View Model
时将Login VM
设置为默认值。Next Window VM
,它将保存该名称和难度设置。<Window x:Class="WPF.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="clr-namespace:ViewModel;assembly=ViewModel" xmlns:views="clr-namespace:WPF_UserControls;assembly=WPF_UserControls" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<DataTemplate DataType="{x:Type vm:LoginViewModel}">
<views:Login/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:NextWindowViewModel}">
<views:NextWindow/>
</DataTemplate>
</Window.Resources>
<Window.DataContext>
<vm:MainViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ContentControl Grid.ColumnSpan="5" Content="{Binding CurrentViewModel}"/>
<Button Grid.Row="1" Content="Close" Command="{Bidning CloseCommand}"/>
</Grid>
</Window>
当我查看您的问题时,我看到该字段警告“MainWindow.SelectedDegree”,它不仅是一个字段(不适用于 WPF 绑定,需要是一个属性),而且 MvvM 并不是真正的工作方式。 如果您需要更多帮助,请告诉我们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.