首页 > 解决方案 > 如何从 c# 中的 ViewModelHelper 关闭窗口(XAML)?

问题描述

我想从onTimeOutCommand() 方法中执行onCloseCommand(object sender) 方法,但是我不知道如何传递从该方法传递的所需参数?

请参考以下代码片段。

XAML 代码:

x:name = "Recorder" // window name define in the begining


//below command is used for closing this window when user clicks on close button

Command = "{Binding CloseCommand}" CommandParameter="{Binding ElementName=Recorder}"

视图模型代码:

CloseCommand = new DelegateCommand<object>(helper.onCloseCommand);

ViewModelHelper 代码:

Note: onCloseCommand() methodis working as per expectation
onCloseCommand(object sender) // This method is used for closing the window on clicking on close button of this window
{
    if(sender != null && send is window)
    {
         (sender as window).close();
    }
}

onTimeOutCommand() // this method is used for closing the window (the window which is passed in onCloseCommand() method) automaticlly after time out of the recording
{
      how to perform onCloseCommand() from this method?
}

标签: c#wpfmvvmdata-bindingprism

解决方案


您应该使用AttachProperty来关闭您的窗口。

public static class Attach
{
    #region CloseProperty
    public static DependencyProperty WindowCloseProperty = DependencyProperty.RegisterAttached("WindowClose",
        typeof(bool), typeof(Attach),
        new UIPropertyMetadata(false, WindowClosePropertyChangedCallback));

    private static void WindowClosePropertyChangedCallback(DependencyObject dependencyObject,
        DependencyPropertyChangedEventArgs eventArgs)
    {
        var window = (Window)dependencyObject;
        if (window != null && (bool)eventArgs.NewValue)
            window.Close();
    }

    public static bool GetWindowClose(DependencyObject obj)
        => (bool)obj.GetValue(WindowCloseProperty);

    public static void SetWindowClose(DependencyObject obj, bool value)
    {
        obj.SetValue(WindowCloseProperty, value);
    }

    #endregion
}

在 XAML 中

<Window x:Class="MyProject.MyWindow"
xmlns:helper="clr-namespace:MyProject.Helper;assembly=MyProject"
    helper:Attach.WindowClose="{Binding IsWindowClose}">

ViewModel当你设置为真你的IsWindowClose窗口关闭

  public bool IsWindowClose
  {
      get => _isWindowClose;
      set => SetProperty(ref _isWindowClose, value);
  }

推荐阅读