mvvm toolkit 子窗口和父窗口参数传递程序实现案例
时间: 2023-12-04 16:03:50 浏览: 236
下面是一个使用MVVM Toolkit实现子窗口和父窗口参数传递的简单示例:
首先,创建一个MainWindow和一个ChildWindow,分别表示父窗口和子窗口。
MainWindow.xaml:
```xaml
<Window x:Class="MVVMToolkitExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MVVMToolkitExample"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Open Child Window" Command="{Binding OpenChildWindowCommand}"/>
</Grid>
</Window>
```
MainWindow.xaml.cs:
```csharp
using System.Windows;
namespace MVVMToolkitExample
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
}
}
```
ChildWindow.xaml:
```xaml
<Window x:Class="MVVMToolkitExample.ChildWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MVVMToolkitExample"
Title="ChildWindow" Height="300" Width="300">
<Grid>
<TextBlock Text="{Binding Message}"/>
</Grid>
</Window>
```
ChildWindow.xaml.cs:
```csharp
using System.Windows;
namespace MVVMToolkitExample
{
public partial class ChildWindow : Window
{
public ChildWindow()
{
InitializeComponent();
DataContext = new ChildWindowViewModel();
}
}
}
```
接下来,创建ViewModel类来处理窗口之间的参数传递。
MainWindowViewModel.cs:
```csharp
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
namespace MVVMToolkitExample
{
public class MainWindowViewModel : ViewModelBase
{
public RelayCommand OpenChildWindowCommand { get; private set; }
public MainWindowViewModel()
{
OpenChildWindowCommand = new RelayCommand(() =>
{
// 创建一个消息对象,传递参数
Messenger.Default.Send(new OpenChildWindowMessage("Hello from MainWindow!"));
});
}
}
}
```
ChildWindowViewModel.cs:
```csharp
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
namespace MVVMToolkitExample
{
public class ChildWindowViewModel : ViewModelBase
{
private string _message;
public string Message
{
get { return _message; }
set { Set(ref _message, value); }
}
public ChildWindowViewModel()
{
// 注册消息接收器,处理参数传递
Messenger.Default.Register<OpenChildWindowMessage>(this, message =>
{
Message = message.Message;
});
}
}
}
```
最后,我们需要创建一个消息类来传递参数。
OpenChildWindowMessage.cs:
```csharp
namespace MVVMToolkitExample
{
public class OpenChildWindowMessage
{
public string Message { get; private set; }
public OpenChildWindowMessage(string message)
{
Message = message;
}
}
}
```
现在,当点击父窗口的按钮时,将会打开一个子窗口,并且子窗口中的TextBlock将显示父窗口传递的参数。
请注意,以上示例使用了MVVM Light Toolkit来简化MVVM模式的实现。你可以根据自己的需求选择适合的MVVM框架或者手动实现。
阅读全文