c# - 如何从 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?
}
解决方案
您应该使用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);
}
推荐阅读
- twilio - 如何允许用户在 Electron 应用程序中按下按钮,将他们重定向到自动拨打电话的 Twilio Flex 仪表板中?
- python - 提取 3D 数据帧的一部分
- sql - 从 hive 中的时间戳中提取年份
- c - 如何调试 write() 函数?
- java - 你如何从 Javalin 中读取多个 body 参数?
- shell - jenkins ssh 到服务器无法存储为变量
- javascript - 按下箭头键会影响接受输入值的函数的结果
- c++ - 铸造 std::shared_ptr
> 到 std::shared_ptr - python - 根据模式使用额外的空列来处理 json_normalize
- azure-devops - 回购权限详细报告