【问题标题】:RoutedUICommands and currently focused elementRoutedUICommands 和当前关注的元素
【发布时间】:2013-08-14 07:28:03
【问题描述】:
RoutedUICommand 是否会自动到达当前聚焦的控件(假设控件具有正确的命令绑定)?例如:
<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,而不在Button 上声明明确的CommandTarget?谢谢。
【问题讨论】:
标签:
.net
wpf
xaml
wpf-controls
routed-commands
【解决方案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");
}
}
}