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

时间:2015-07-17 19:49:18

标签: c# wpf wpf-controls

我在WPF中有可编辑的组合框,我想从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;
        }


    }

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

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

点击WPF Editable ComboBox