我正在尝试使用搜索框和结果列表创建一个小模态窗口。 我的目标是在搜索后将焦点放在List的第一个元素中。
问题
不幸的是,我陷入了搜索后我的焦点落在窗户上的情况。
我的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
在我的命令执行后获得焦点。
我试图手动设置焦点元素,但它没有效果。
问题
有人可以向我解释,为什么焦点会默认落在窗口上?
有人可以建议一种方法,我可以自己控制焦点并避免这种默认行为吗?
DataGrid
需要一些时间来重绘自己,然后才能看到我要关注的行。属性
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();
}
}
答案 0 :(得分:0)
我无法找到解释为什么KeyboardFocus落在我的窗口上或为什么我设置焦点的尝试没有效果。
但我终于找到了一个解决方案,我的尝试在哪里工作。
我使用带有BackgroundPriority的Dispatcher调用我的方法在设置焦点到窗口之后设置焦点。这适用于键盘和鼠标输入。
private void ViewModel_SuppliersAdded()
{
Dispatcher.BeginInvoke(new Action(SetFocusToFirstRow), DispatcherPriority.Background);
}