wpf 修改输入框 光标_在WPF C#中将光标焦点设置为可编辑组合框

这篇博客讨论了在WPF中如何使可编辑的ComboBox获得焦点并显示为编辑模式,而不是只显示选中项。作者通过在ComboBox的Loaded事件中找到内部的TextBox并设置焦点和光标位置实现了这一目标。此外,还提供了两种解决方案:一种是创建FocusExtension附加属性,另一种是直接清空ComboBox的Text并设置焦点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have editable combobox in WPF and I want to set focus from C#,

I am using Combobox.Focus(), but it shows only selection but I want edit option where user can start entering.

Update : Figured out FIX

I ended up adding 'Loaded' Event to the Combobox and Wrote following Code to get focus in and it worked Fine

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;

}

}

Talk1:

Why wouldn't it work if I write the same code somewhere else? (Say, in a button's click handler?)

Solutions1

Try Creating a Focus Extension like below, and set the attached property to the text box and bind it.

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

Talk1:

I don't have TextBox under Combobox as Custom Template, I have editable combobox. Still I can use this?

Talk2:

yes you can use it for any control as its an Attached property.

Talk3:

Is the OnLostFocus required there? I don't understand, can you explain?

Solutions2

If I understand you correctly, you have following situation: you set focus to ComboBox and observe selected text inside editable area, but you want it to be empty with only blinking caret inside. If so, you can do it this way:

ComboBox.Focus();

ComboBox.Text = String.Empty;

Solutions3

Have a look at this. It might help you

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值