[英]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.