简体   繁体   English

从代码背后触发RelayCommand

[英]Triggering RelayCommand from code-behind

I have a Main Page for my application that is formed froma number of other windows. 我的应用程序主页由许多其他窗口组成。 One of which is the settings for my applications and is open/closed by clicking a button from my Main Page. 其中之一是我的应用程序的设置,可通过单击我的主页上的按钮来打开/关闭。 This window has a View Model as well as two buttons, Save and Cancel. 该窗口具有一个视图模型以及两个按钮,保存和取消。 Pressing Cancel is used to restore the previous settings and Save just stores them. 按取消用于恢复以前的设置,而保存仅存储它们。 Now, when I use the main menu to close the Properties I want the Cancel to be called and am wondering about the best way to do this. 现在,当我使用主菜单关闭“属性”时,我想调用“取消”,并且想知道执行此操作的最佳方法。

So in my view model I have something like this: 所以在我的视图模型中,我有这样的东西:

public RelayCommand CancelRC { get; private set; }

public  PropertiesViewModel
{
    CancelRC = new RelayCommand(RestoreProperties)
}

private RestoreProperties
{
     // Restore
}

In my MainPage.xaml.cs 在我的MainPage.xaml.cs中

private void Properties_Click(object sender, RoutedEventArgs e)
{
    if (PropertiesForm.Visibility == Visibility.Collapsed)
    {
        PropertiesForm.Visibility = Visibility.Visible;
        PropertiesForm.IsSelected = true;
    }
    else
    {
        PropertiesForm.Visibility = Visibility.Collapsed;
        IncidentForm.IsSelected = true;

        // Send a Cancel relaycommand to the Properties View Model?
    }
}

The obvious solution to me is to trigger the RelayCommand manually but I am not sure this is the most appropriate way to do it and I am not sure how you would trigger that anyway. 对我来说,显而易见的解决方案是手动触发RelayCommand,但是我不确定这是最合适的方法,并且我不确定您将如何触发它。 So it this the way to do it or is there a more preferred way to do something like this? 是以这种方式做到这一点,还是有一种更喜欢的方式来做这样的事情?

Similarly is manually hiding and showing the Properties via the Main Page like this the best way to do it? 同样,通过这样的主页手动隐藏和显示属性是最好的方法吗?

Remove the Properties_Click method and in your xaml do the following: 删除Properties_Click方法,然后在您的xaml中执行以下操作:

<Button Command="{Binding CancelRC}">Properties</Button>

This will cause the button to use RelayCommand.CanExecute and RelayCommand.Execute with no code on your part. 这将导致该按钮使用RelayCommand.CanExecute和RelayCommand.Execute而无需编写任何代码。 The code assumes the window datacontext is set to your View Model. 该代码假定窗口datacontext设置为您的视图模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM