我在 WPF 中有可编辑的组合框,我想从 C# 设置焦点,
我正在使用 Combobox.Focus(),但它只显示选择,但我想要用户可以开始输入的编辑选项。
更新:找出 FIX
我最终将“加载”事件添加到组合框并编写了以下代码以获得焦点并且它工作正常
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;
}
}
最佳答案
尝试创建一个像下面这样的焦点扩展,并将附加属性设置为文本框并绑定(bind)它。
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
<TextBox Extension:FocusExtension.IsFocused="{Binding IsProviderSearchFocused}"/>
关于c# - 在 WPF C# 中将光标焦点设置为可编辑的组合框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31483650/