RoutedUICommands和当前关注的元素

时间:2013-08-14 07:28:03

标签: .net wpf xaml wpf-controls routed-commands

RoutedUICommand是否自动到达当前关注的控件(如果控件具有正确的命令绑定)? E.g:

<Button Focusable="False" Command="ApplicationCommands.Open" Content="Open" />

<UserControl Name="ctl" Focusable="True" IsTabStop="True">
    <UserControl.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Open" CanExecute="CanOpen" Executed="OpenExecuted"/>
        <!-- ... -->
    </UserControl.CommandBindings>
</UserControl>

ApplicationCommands.Open在有焦点时会UserControl到达CommandTarget,而不会在Button上声明明确的{{1}}吗?谢谢。

1 个答案:

答案 0 :(得分:1)

已编辑 我尝试了它,但似乎并非如此,至少不适用于UserControl

确实,当您在命令源上指定FocusManager.IsFocusScope="true"时。一个类似的问题answered

XAML:

<Window x:Class="TestApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="200" Width="320">
    <StackPanel>
        <Button FocusManager.IsFocusScope="true" Focusable="False" Command="ApplicationCommands.Open" Content="Open: Binding MainWindow" Width="200" CommandTarget="{Binding MainWindow}"/>
        <Button FocusManager.IsFocusScope="true" Focusable="False" Command="ApplicationCommands.Open" Content="Open: no CommandTarget" Width="200" />
        <Button FocusManager.IsFocusScope="true" Focusable="False" Command="ApplicationCommands.Open" Content="Open: Binding ElementName=ctl" Width="200" CommandTarget="{Binding ElementName=ctl}"/>
        <Button FocusManager.IsFocusScope="true" Focusable="False" Content="Where is the focus?" Click="Button_Click"  Width="200"/>
        <UserControl Name="ctl" Focusable="True" IsTabStop="True">
            <UserControl.CommandBindings>
                <CommandBinding Command="ApplicationCommands.Open" CanExecute="CanOpen" Executed="OpenExecuted"/>
            </UserControl.CommandBindings>
        </UserControl>
    </StackPanel>
</Window>

C#:

using System.Windows;
using System.Windows.Input;

namespace TestApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ctl.Focus();
        }

        private void CanOpen(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void OpenExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("OpenExecuted");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var focusedElement = FocusManager.GetFocusedElement(this);
            MessageBox.Show(focusedElement != null ? focusedElement.GetType().ToString() : "none");
        }
    }
}