Keep focus on another control while selecting items in a ListBox
I have TextBox which should always be in focus. At the same time I have as list box. When user clicks on certain item in this listobox the item clicked gets focus.
I tried to set Focusable="false" for each ListBoxItem in my ListBox but in this case no item can be selected. I found following cod开发者_运维百科e using dotPeek:
private void HandleMouseButtonDown(MouseButton mouseButton)
{
if (!Selector.UiGetIsSelectable((DependencyObject) this) || !this.Focus())
return;
...
}
Is there any way to solve my problem?
You could handle PreviewMouseDown on the ListBoxItems and mark the event as Handled which will stop the focus being transferred.
You can set e.Handled = true
because MouseButtonEventArgs is a RoutedEventArgs.
This demo works to keep focus on the TextBox:
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>
Code Behind
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;
}
}
}
精彩评论