【问题标题】:Is there any way to alias commands in WPF?有没有办法在 WPF 中给命令起别名?
【发布时间】:2011-07-03 03:29:39
【问题描述】:

有没有办法在 WPF 中有效地“别名”命令?我的情况是这样的:我创建了一个应用程序,它在具有许多自定义画布的图形编辑器的上下文中使用 ApplicationCommands.Delete。这些画布上的一些控件使用 TextBox,但问题是:TextBox 不响应 ApplicationCommands.Delete,它响应 EditorCommands.Delete。有什么方法可以干净地让 TextBox 响应 ApplicationCommands.Delete 而无需在每个 TextBox 实例上进行子类化或手动设置绑定?

【问题讨论】:

    标签: wpf routed-commands


    【解决方案1】:

    为了回答您的具体问题,我知道无法将两个单独的路由命令视为同一命令。但是因为ApplicationCommands.Delete是一个路由命令,在它被传递到它的目标之后,TextBox并且没有命令绑定,它会开始冒泡。因此,满足您要求的最简单的解决方案是在TextBox 之间的某个位置安装ApplicationCommands.Delete 的命令绑定,一直到可能包括Window,以实现您想要的行为。

    这是一个在父 Grid 上安装处理程序的示例,该处理程序将“正确”命令发送到焦点元素,在这种情况下将是 TextBox

    <Grid>
        <Grid.CommandBindings>
            <CommandBinding Command="ApplicationCommands.Delete" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed"/>
        </Grid.CommandBindings>
        <DockPanel>
            <Menu DockPanel.Dock="Top">
                <MenuItem Header="_Edit">
                    <MenuItem Header="_Delete" Command="ApplicationCommands.Delete"/>
                </MenuItem>
            </Menu>
            <StackPanel>
                <TextBox Text="Some text"/>
            </StackPanel>
        </DockPanel>
    </Grid>
    

    这是代码隐藏:

    private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }
    
    private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        EditingCommands.Delete.Execute(null, Keyboard.FocusedElement);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 2011-02-02
      相关资源
      最近更新 更多