【问题标题】:Set Cursor Focus into Editable Combobox in WPF C#在 WPF C# 中将光标焦点设置为可编辑组合框
【发布时间】:2015-07-17 19:49:17
【问题描述】:

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

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

更新:解决了问题

我最终将“加载”事件添加到组合框并编写了以下代码以获取焦点,并且效果很好

    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;
        }


    }

【问题讨论】:

  • 如果我在其他地方编写相同的代码,为什么它不起作用? (比如说,在按钮的点击处理程序中?)

标签: c# wpf wpf-controls


【解决方案1】:

尝试像下面这样创建一个焦点扩展,并将附加属性设置为文本框并绑定它。

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}"/>

【讨论】:

  • 我在 Combobox 下没有 TextBox 作为自定义模板,我有可编辑的组合框。我还能用这个吗?
  • 是的,您可以将其作为附加属性用于任何控件。
  • 那里需要OnLostFocus 吗?没看懂,能解释一下吗?
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    点击WPF Editable ComboBox

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2014-04-24
      相关资源
      最近更新 更多