在WPF C#中将光标焦点设置为可编辑的Combobox

我在WPF中有可编辑的combobox,我想从C#设置焦点,

我正在使用Combobox.Focus(),但它只显示选择但我想要编辑选项,用户可以开始输入。

更新:想出FIX

我最终在Combobox中添加了’Loaded’事件并写了以下代码以获得重点并且它工作得很好

private void LocationComboBox_Loaded(object sender, RoutedEventArgs e) { ComboBox cmBox = (System.Windows.Controls.ComboBox)sender; var textBox = (cmBox.Template.FindName("PART_EditableTextBox", cmBox) as TextBox); if (textBox != null) { textBox.Focus(); textBox.SelectionStart = textBox.Text.Length; } } 

尝试创建如下所示的焦点扩展,并将附加属性设置为文本框并绑定它。

 public static class FocusExtension { public static bool GetIsFocused(DependencyObject obj) { return (bool)obj.GetValue(IsFocusedProperty); } public static void SetIsFocused(DependencyObject obj, bool value) { obj.SetValue(IsFocusedProperty, value); } public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached( "IsFocused", typeof(bool), typeof(FocusExtension), new UIPropertyMetadata(false, OnIsFocusedPropertyChanged)); private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var uie = (UIElement)d; if ((bool)e.NewValue) { OnLostFocus(uie, null); uie.Focus(); } } private static void OnLostFocus(object sender, RoutedEventArgs e) { if (sender != null && sender is UIElement) { (sender as UIElement).SetValue(IsFocusedProperty, false); } } } 

XAML

   

如果我理解正确,您有以下情况:您将焦点设置为ComboBox并在可编辑区域内观察所选文本,但您希望它是空的,内部只有闪烁的插入符号。 如果是这样,你可以这样做:

 ComboBox.Focus(); ComboBox.Text = String.Empty; 

看看这个。 它可能对你有所帮助

单击WPF可编辑combobox