0

Lets say I have next layout:

Window
  UserControl
    UserControl
      UserControl
        Button
        GridControl
          GridCell

And lets say that GridCell currently has Keyboard focus. If a user clicks on button. a message is displayed to user to confirm action. No matter of what choice the user selected (Yes or No), a focus should return to a CurrentCell on GridControl. By default, after a user selected some option, a focus would return to Window (reported by Snoop). I would assume that a Button that was clicked would retain focus, but apparently not.

Handling of button Command is done in ViewModel (MVVM).

How do I return keyboard focus to a current cell in grid?

4

1 回答 1

0

您可以通过FocusManager.IsFocusScope="true"在按钮上设置或者如果有多个按钮是它们所在的父元素(例如StackPanel或其他)来非常安全地解决此问题。

如果您使用RoutedCommands. 基本上RoutedCommands并不总是按照您期望它们在焦点范围内的方式工作。听起来您正在直接绑定到视图模型上的命令,但这应该不是问题。如果您想了解有关该RoutedCommand问题的更多信息,请查看此代码项目文章

这是我验证此工作的示例代码,供您参考。

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid Margin="25">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition />
        </Grid.RowDefinitions>

        <!--You could also have the FocusManager.IsFocusScope set on the Border instead-->
        <Border Margin="0,0,0,15">
            <Button FocusManager.IsFocusScope="True" Click="ButtonBase_OnClick">Click me!</Button>
        </Border>

        <TextBox Grid.Row="1" x:Name="MessageTextBox"></TextBox>
    </Grid>
</Window>

C#:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Clicked, message: " + MessageTextBox.Text);
    }
}  
于 2013-04-24T12:08:01.203 回答