我想在单击时将ListBox项模板的特定实例放在键盘上。实例没有获得键盘焦点,而是失去了焦点。
我使用.NET Framework 4.6.1。如果重要,则WPF用户控件将嵌入在WinForms面板中。我见过this answer,但由于以下原因我认为它没有用:
ListBoxItem
(因为我使用ListBox.ItemTemplate
,而且我不知道我可以将ItemsSource与ListBoxItem
s一起使用)。数据资源:
<XmlDataProvider x:Key="xmlData">
<x:XData>
<Inventory xmlns="">
<ClockData />
<ClockData />
</Inventory>
</x:XData>
</XmlDataProvider>
主要UserControl的内容:
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ItemsSource="{Binding Source={StaticResource xmlData}, XPath=Inventory/ClockData}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True"></WrapPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<wpf:TimeSpanPicker Width="100" Height="50"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<wpf:TimeSpanPicker>
:
<UserControl x:Class="wpf_timespanpicker.TimeSpanPicker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:wpf_timespanpicker"
mc:Ignorable="d"
d:DesignHeight="170" d:DesignWidth="365"
KeyboardNavigation.TabNavigation="Continue"
IsTabStop="True"
Focusable="True"
GotKeyboardFocus="UserControl_GotKeyboardFocus"
LostKeyboardFocus="UserControl_LostKeyboardFocus"
PreviewMouseDown="UserControl_PreviewMouseDown">
<Canvas Background="Yellow"></Canvas>
</UserControl>
其代码背后:
private void UserControl_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{ // tracepoint: got kbd focus
}
private void UserControl_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{ // tracepoint: lost kbd focus
}
private void UserControl_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
// tracepoint: mouse down => kbd focus
Keyboard.Focus(this);
// tracepoint: theoretically kbd focus set
}
使用上面的代码,当我单击ListBox项时,在“输出”面板中,每次单击都有以下几行:
mouse down => kbd focus
got kbd focus
theoretically kbd focus set
lost kbd focus
单击的项目获得焦点,然后自动失去焦点。我希望在“输出”面板中看到如下内容:
mouse down => kbd focus
got kbd focus
theoretically kbd focus set
如果我将ListBox
替换为ItemsControl
,则焦点将按我希望的那样工作,输出将与上面写的最后一个输出相同。
Irelevant截图: