【问题标题】:Keep focus on another control while selecting items in a ListBox选择 ListBox 中的项目时,将注意力集中在另一个控件上
【发布时间】:2011-11-25 02:57:08
【问题描述】:

我有应该始终处于焦点的 TextBox。 同时我有列表框。 当用户单击此列表框中的某个项目时,单击的项目将获得焦点。

我尝试为我的 ListBox 中的每个 ListBoxItem 设置 Focusable="false",但在这种情况下,无法选择任何项目。 我使用 dotPeek 找到了以下代码:

private void HandleMouseButtonDown(MouseButton mouseButton)
{
  if (!Selector.UiGetIsSelectable((DependencyObject) this) || !this.Focus())
    return;
  ...
}

有什么办法可以解决我的问题吗?

【问题讨论】:

  • 您想选择列表框中的项目,但不以蓝色突出显示该项目吗?
  • 我希望能够通过鼠标选择列表框项目,但不会失去对文本框的关注。
  • 您可以在列表框的 SelectionChanged 事件中再次设置文本框的焦点。
  • 嗯,是的,它会起作用,但它是一个非常丑陋的解决方案。 TextBox 和 ListBox 位于不同的用户控件中,因此彼此不了解。我宁愿实现自己的列表框和 ListBoxItem,也不愿使用这种方法。
  • 那你可以做一件事。您必须按父/子关系找到该文本框。我不知道这可能与否。如果可能的话,我们可以像在网络上一样找到它。

标签: wpf focus listboxitem


【解决方案1】:

您可以在 ListBoxItems 上处理 PreviewMouseDown 并将事件标记为 Handled,这将停止转移焦点。

您可以设置e.Handled = true,因为MouseButtonEventArgs 是RoutedEventArgs

此演示旨在保持对文本框的关注:

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">
    <StackPanel FocusManager.FocusedElement="{Binding ElementName=textBox}">
        <TextBox  x:Name="textBox" />
        <ListBox x:Name="listBox">
            <ListBoxItem PreviewMouseDown="ListBoxItem_PreviewMouseDown">1</ListBoxItem>
            <ListBoxItem PreviewMouseDown="ListBoxItem_PreviewMouseDown">2</ListBoxItem>
            <ListBoxItem PreviewMouseDown="ListBoxItem_PreviewMouseDown">3</ListBoxItem>
        </ListBox>
    </StackPanel>
</Window>

代码背后

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ListBoxItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            var item = sender as ListBoxItem;
            if (item == null) return;
            listBox.SelectedItem = item;
            e.Handled = true;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多