gpt4 book ai didi

wpf - 如何在WPF中将焦点添加到可编辑的组合框

转载 作者:行者123 更新时间:2023-12-04 13:24:57 25 4
gpt4 key购买 nike

我在 wpf 中使用了一个可编辑的 ComboBox,但是当我尝试从 C# 代码设置焦点时,它只显示选择。但我想选择编辑选项(光标应显示以供用户输入)。

最佳答案

您可以尝试从ComboBox派生并访问内部TextBox,如下所示:

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
}

}

在您的代码中,您将像这样使用它:
<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中的事件处理程序发生冲突。

关于wpf - 如何在WPF中将焦点添加到可编辑的组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2963462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com