如何以键盘为重点单击ListBox的项目模板实例?

时间:2019-04-05 14:34:06

标签: c# wpf listbox

我想在单击时将ListBox项模板的特定实例放在键盘上。实例没有获得键盘焦点,而是失去了焦点。

我使用.NET Framework 4.6.1。如果重要,则WPF用户控件将嵌入在WinForms面板中。我见过this answer,但由于以下原因我认为它没有用:

  • 我不使用ListBoxItem(因为我使用ListBox.ItemTemplate,而且我不知道我可以将ItemsSource与ListBoxItem s一起使用)。
  • 我希望有多个选择,但是我想以编程方式(我希望通过绑定到数据中某个项目的Checked属性)来确定选择了哪些项目,并将选择显示为ItemTemplate中的复选框。
  • li>
  • 我希望在此ListBox中实现具有多个选择的拖放操作。我还没有分析过ListView控件,并且它是否比ListBox能够为我提供更多可拖动选择和放置占位符的帮助。

数据资源:

<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截图:

screenshot

0 个答案:

没有答案