大家好:
我想在后台用C#代码直接改变路由命令当前可执行状态为True,然后直接启动该命令,但是始终不指导该怎么办,还请各位专家指点迷津。
前后端代码如下:
前端XAML:
<Window x:Class="CommandCSharpCalled.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:CommandCSharpCalled" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Window.Resources> <RoutedCommand x:Key="cmd_register"/> </Window.Resources> <Grid> <!--#region 认证用布局和绑定 --> <Grid.CommandBindings> <CommandBinding x:Name="cmd_register" Command="{StaticResource cmd_register}" CanExecute="Cmd_register_CanExecute" Executed="Cmd_register_Executed"/> </Grid.CommandBindings> <Menu Height="24" VerticalAlignment="Top" Margin="0,0,-0.4,0"> <MenuItem FontSize="14" Header="帮助"> <MenuItem Header="注册" Command="{StaticResource cmd_register}"/> <Separator/> </MenuItem> </Menu> <TextBox x:Name="tb_Show" HorizontalAlignment="Left" Height="270" Margin="321,29,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="463"/> <Button x:Name="btn" Content="直接后台更改命令状态并调用命令" HorizontalAlignment="Left" Margin="321,304,0,0" VerticalAlignment="Top" Width="174" Height="51" Click="Btn_Click"/> <!--#endregion--> </Grid> </Window>
后端C#:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace CommandCSharpCalled { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } #region “注册”页面命令 private void Cmd_register_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; e.Handled = true; } private void Cmd_register_Executed(object sender, ExecutedRoutedEventArgs e) { tb_Show.Text = "后端直接更改命令可用状态并调用命令。"; e.Handled = true; } #endregion private void Btn_Click(object sender, RoutedEventArgs e) { //我想在这里改变命令可用状态,然后直接启动命令。 } } }
你的button绑定命令就可以了,不需要事件
满足你的需求,但感觉你的业务逻辑可以优化一下,这样用命令并不太好
#region “注册”页面命令
bool cmdCanExecute = false;
private void Cmd_register_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = cmdCanExecute;
e.Handled = true;
}
private void Cmd_register_Executed(object sender, ExecutedRoutedEventArgs e)
{
tb_Show.Text = "后端直接更改命令可用状态并调用命令。";
e.Handled = true;
}
#endregion
private void Btn_Click(object sender, RoutedEventArgs e)
{
//我想在这里改变命令可用状态,然后直接启动命令。
ICommand cmd = (ICommand)this.FindResource("cmd_register");
//命令状态可以单独定义一个变量,不一定要用 tb_Show.IsEnabled
cmdCanExecute = true;
//参数自己定义,这里用null
cmd.Execute(null);
}