如何将焦点添加到 WPF 中的可编辑组合框 [英] How to add a focus to an editable ComboBox in WPF
问题描述
我在 wpf 中使用了一个可编辑的 ComboBox,但是当我尝试从 C# 代码设置焦点时,它只显示选择.但我想选择编辑选项(光标应显示以供用户输入).
I am using an editable ComboBox in wpf but when i try to set focus from C# code, it is only shows selection. but i want to go for edit option (cursor should display for user input).
推荐答案
您可以尝试从 ComboBox 派生并访问内部 TextBox,如下所示:
You might try deriving from ComboBox and access the internal TextBox, like this:
public class MyComboBox : ComboBox
{
TextBox _textBox;
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_textBox = Template.FindName("PART_EditableTextBox", this) as TextBox;
if (_textBox != null)
{
_textBox.GotKeyboardFocus += _textBox_GotFocus;
this.Unloaded += MyComboBox_Unloaded;
}
}
void MyComboBox_Unloaded(object sender, System.Windows.RoutedEventArgs e)
{
_textBox.GotKeyboardFocus -= _textBox_GotFocus;
this.Unloaded -= MyComboBox_Unloaded;
}
void _textBox_GotFocus(object sender, System.Windows.RoutedEventArgs e)
{
_textBox.Select(_textBox.Text.Length, 0); // set caret to end of text
}
}
在您的代码中,您会像这样使用它:
In your code you would use it like this:
<Window x:Class="EditableCbox.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:EditableCbox"
Title="Window1" Height="300" Width="300">
...
<local:MyComboBox x:Name="myComboBox" IsEditable="True" Grid.Row="0" Margin="4">
<ComboBoxItem>Alpha</ComboBoxItem>
<ComboBoxItem>Beta</ComboBoxItem>
<ComboBoxItem>Gamma</ComboBoxItem>
</local:MyComboBox>
...
</Window>
然而,这个解决方案有点危险,因为在即将推出的 WPF 版本中,Microsoft 可能还会决定添加 GotKeyboardFocus 事件处理程序(或类似的事件处理程序),这可能会与 MyComboBox 中的事件处理程序发生冲突.
This solution slightly dangerous, however, because in upcoming versions of WPF, Microsoft might decide also to add a GotKeyboardFocus event handler (or similar event handlers), which might get in conflict in with the event handler in MyComboBox.
这篇关于如何将焦点添加到 WPF 中的可编辑组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!