欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF MVVM 如何在 ViewModel 中关闭界面窗口

程序员文章站 2022-07-13 22:37:33
...

01 xaml 

<Button Width="80" 
        Command="{Binding CancelCmd}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">
</Button>

02 后台cs 

private CommandBase cancelCmd;

public CommandBase CancelCmd
{
    get
    {
        if (cancelCmd == null)
        {
            cancelCmd = new CommandBase(CloseApp, CancelCanExcute);
        }
        return cancelCmd;
    }
}

void CloseApp(object o)
{
    var win = o as System.Windows.Window;
    win.Close();
}

bool CancelCanExcute(object o) { return true; }