参考自:https://blog.csdn.net/zang141588761/article/details/79230319
1.使用MVVM时,有多个窗体,但只关闭当前窗体,使用Application.Current.Shutdown(-1); Process.GetCurrentProcess().Kill();就会将所有窗体全部关闭。肯定不行。
2.用附加属性控制窗体的打开与关闭
public static class DialogCloser
{
public static readonly DependencyProperty DialogResultProperty =
DependencyProperty.RegisterAttached(
"DialogResult",
typeof(bool?),
typeof(DialogCloser),
new PropertyMetadata(DialogResultChanged));
private static void DialogResultChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var window = d as Window;
if (window != null)
{
if (bool.Parse(e.NewValue.ToString()))
{
window.ShowDialog();
}
else
{
window.Close();
}
}
}
public static void SetDialogResult(Window target, bool? value)
{
target.SetValue(DialogResultProperty, value);
}
}
3.XAML代码:在窗体上绑定对应ViewModel里的DialogResult
<Window x:Class="MonitorValueManager.View.DeviceDetailView"
xmlns:common="clr-namespace:MonitorValueManager.Common"
mc:Ignorable="d"
Height="200" Width="200" ResizeMode="NoResize"
common:DialogCloser.DialogResult="{Binding DialogResult}">
4.对应VIewModel里的代码:需要进行通知
public class DeviceDetailViewModel : ObservableObject
{
private bool _dialogresult = true;
public bool DialogResult
{
get { return _dialogresult; }
set
{
_dialogresult = value;
RaisePropertyChanged();
}
}
5.调用窗体时不能直接调用窗体的ShowDialog()方法,不然会报错或窗体不显示