質問

Is there any way to effectively "alias" commands in WPF ? My situation is this : I've created an application that uses ApplicationCommands.Delete in the context of a graphical editor that has a number of customized canvases. Some of the controls that are on these canvases use TextBoxes, but here's the problem : TextBox doesn't respond to ApplicationCommands.Delete, it responds to EditorCommands.Delete. Is there any way to cleanly get TextBox to respond to ApplicationCommands.Delete without subclassing or manually setting bindings on every TextBox instance ?

役に立ちましたか?

解決

To answer your specific question, I know of no way to cause two separate routed commands to be treated as the same command. But because ApplicationCommands.Delete is a routed command, after it is delivered to its target, the TextBox and there is no command binding, it will begin bubbling up. So the simplest solution that meets your requirements is to install a command binding for ApplicationCommands.Delete somewhere inbetween the TextBox all the way up to and possibly including the Window, that implements the behavior you desire.

Here's an example that installs a handler on a parent Grid that sends the "right" command the the focused element which in this case will be a 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>

and here's the code-behind:

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);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top