我使用WPF中可编辑ComboBox但是当我尝试将焦点设置在C#代码,它只是显示的选择.但我想去编辑选项(光标应显示用户输入).
你可以试试这段代码:
var textBox = (comboBox.Template.FindName("PART_EditableTextBox", comboBox) as TextBox);
if (textBox != null)
{
textBox.Focus();
textBox.SelectionStart = textBox.Text.Length;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
根据上面 user128300 的回答,我想出了一个稍微简单的解决方案。在构造函数或 ContextChangedHandler 中,代码在将焦点放在 UI 元素上之前等待控件加载
myComboBox.GotFocus += MyComboBoxGotFocus;
myComboBox.Loaded += (o, args) => { myComboBox.Focus(); };
Run Code Online (Sandbox Code Playgroud)
然后在焦点偶数处理程序中我选择从开始到结束的所有文本
private void MyComboBoxGotFocus(object sender, RoutedEventArgs e)
{
var textBox = myComboBox.Template.FindName("PART_EditableTextBox", myComboBox) as TextBox;
if (textBox != null)
textBox.Select(0, textBox.Text.Length);
}
Run Code Online (Sandbox Code Playgroud)
在 xaml 中,组合框是可编辑的。通过在用户键入键时选择所有文本来重置以前的值
<ComboBox x:Name="myComboBox" IsEditable="True" />
Run Code Online (Sandbox Code Playgroud)
小智 3
您可以尝试从 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
}
}
Run Code Online (Sandbox Code Playgroud)
在您的代码中,您将像这样使用它:
<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>
Run Code Online (Sandbox Code Playgroud)
但是,此解决方案有点危险,因为在即将推出的 WPF 版本中,Microsoft 可能还决定添加 GotKeyboardFocus 事件处理程序(或类似的事件处理程序),这可能会与 MyComboBox 中的事件处理程序发生冲突。
| 归档时间: |
|
| 查看次数: |
7551 次 |
| 最近记录: |