命令后的 WPF 焦点 - 为什么它落在我的 Window 上?

WPF Focus after Command - Why does it land on my Window?

我正在尝试制作一个带有搜索框和结果列表的小模式 window。 我的目标是搜索后焦点落在列表的第一个元素上。

问题

不幸的是,搜索后我的注意力集中在 window 本身。

我的 TextBox 有一个 InputBinding 在输入时触发以执行搜索:

<TextBox Grid.Column="1" Grid.Row="1" 
         Text="{Binding Supplier.LeverandorNavn, UpdateSourceTrigger=PropertyChanged}" 
         x:Name="txtBoxSupplierName" Width="150" 
         HorizontalAlignment="Left" VerticalAlignment="Top" 
         TabIndex="1">
        <TextBox.InputBindings>
            <KeyBinding Key="Return" Command="{Binding SearchCommand}" />
        </TextBox.InputBindings>
</TextBox>

我一直在尝试使用 Snoop 来理解事件的流程。 如此处所示,KeyDown 由我的 txtBoxSupplerName Textbox 处理。 但是我不明白为什么 levWindow 在我的命令执行后获得焦点。

我尝试手动设置焦点元素,但没有效果。

问题

谁能给我解释一下,为什么默认情况下焦点会落在 window 上?

有人可以建议一种方法,告诉我如何自己控制焦点并避免这种默认行为吗?

属性

public ClientLeverandor ValgtLeverandør
{
    get { return _valgtLeverandør; }
    set { SetProperty(ref _valgtLeverandør, value, nameof(ValgtLeverandør)); }
}
public ObservableCollection<ClientLeverandor> Leverandører
{
    get { return _leverandører; }
    private set { SetProperty(ref _leverandører, value, nameof(Leverandører)); }
}
public ListCollectionView LeverandørView
{
    get { return _leverandørView; }
    set { SetProperty(ref _leverandørView, value, nameof(LeverandørView)); }
}

命令执行

using (BusyIndicator.ShowInScope(Strings.HenterData_BusyText))
{
    var leverandører = await SøgLeverandører(Supplier);

    if (leverandører.Any())
    {
        Leverandører.Clear();
        foreach (var lev in leverandører) Leverandører.Add(lev);
        ValgtLeverandør = Leverandører[1];

        SuppliersAdded?.Invoke();
    }
}

我找不到解释为什么 KeyboardFocus 落在我的 window 上或者为什么我尝试设置焦点没有效果。

但我终于找到了解决方案,我的尝试奏效了。

我使用具有 BackgroundPriority 的 Dispatcher 来调用我的方法来设置焦点 after 无论将焦点设置到 window。这适用于键盘和鼠标输入。

    private void ViewModel_SuppliersAdded()
    {
        Dispatcher.BeginInvoke(new Action(SetFocusToFirstRow), DispatcherPriority.Background);
    }