WPF mvvm框架Stylet使用教程-窗体交互用法
窗体操作
打开窗体
在stylet框架中,要打开一个窗口或者对话框,只需要直接使用窗口管理器
在要使用的ViewModel中注入IWindowManager
,然后使用他的方法操作窗口。
ShowDialog(object viewModel)
模态显示ShowWindow(object viewModel)
非模态显示ShowMessageBox()
消息框
示例:
在View中增加三个按钮
<ButtonWidth="140"Height="57"Margin="781,188,0,0"HorizontalAlignment="Left"VerticalAlignment="Top"Command="{s:Action ShowDialogAbout}"Content="打开弹窗"FontSize="20" /><ButtonWidth="140"Height="57"Margin="781,269,0,0"HorizontalAlignment="Left"VerticalAlignment="Top"Command="{s:Action ShowAbout}"Content="打开窗口"FontSize="20" /><ButtonWidth="140"Height="57"Margin="781,356,0,0"HorizontalAlignment="Left"VerticalAlignment="Top"Command="{s:Action ShowMsg}"Content="打开消息框"FontSize="20" />
在对应ViewModel中,构造方法中注入一个IWindowManager, 在ViewModel中获取到IWindowManager 对象
private IWindowManager _windowManager;public ShellViewModel(IWindowManager windowManager)
{_windowManager= windowManager;
}
然后实现三个方法,分别使用IWindowManager 的方法ShowDialog()、ShowWindow()、ShowMessageBox()
打开窗口和消息框
/// <summary>
/// 打开一个About窗口,模态显示
/// </summary>
public void ShowDialogAbout()
{_windowManager.ShowDialog(new AboutViewModel());
}/// <summary>
/// 打开一个About窗口,非模态显示
/// </summary>
public void ShowAbout()
{_windowManager.ShowWindow(new AboutViewModel());
}/// <summary>
/// 打开一个消息对话框,输入参数跟windows消息框一样
/// </summary>
public void ShowMsg()
{_windowManager.ShowMessageBox("这是一个重要消息", "重要", MessageBoxButton.OK, MessageBoxImage.Information);}
完整的ShellViewModel.cs代码如下
public class ShellViewModel : Screen{public void ChangeTitle(){}private IWindowManager _windowManager;public ShellViewModel(IWindowManager windowManager){_windowManager= windowManager;}/// <summary>/// 打开一个About窗口,模态显示/// </summary>public void ShowDialogAbout(){_windowManager.ShowDialog(new AboutViewModel());}/// <summary>/// 打开一个About窗口,非模态显示/// </summary>public void ShowAbout(){_windowManager.ShowWindow(new AboutViewModel());}/// <summary>/// 打开一个消息对话框,输入参数跟windows消息框一样/// </summary>public void ShowMsg(){_windowManager.ShowMessageBox("这是一个重要消息", "重要", MessageBoxButton.OK, MessageBoxImage.Information);}}
运行便可以操作窗口打开了
关闭窗体
关闭窗体需要使用基类Screen中的方法RequestClose()
,
在窗体上增加一个关闭按钮,绑定方法Close
<ButtonWidth="39"Height="26"Margin="21,21,0,0"HorizontalAlignment="Left"VerticalAlignment="Top"Command="{s:Action Close}"Content="关闭" />
然后在ViewModel中实现关闭方法
public void Close()
{this.RequestClose();
}
就可以实现窗体关闭