首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在WPF C#中将光标焦点设置为可编辑组合框

在WPF C#中将光标焦点设置为可编辑组合框
EN

Stack Overflow用户
提问于 2015-07-17 19:49:17
回答 3查看 4.3K关注 0票数 4

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

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

更新:计算出修复

最后,我将“加载”事件添加到Combobox中,并编写了下面的代码以获得焦点,而且效果很好。

代码语言:javascript
复制
    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;
        }


    }
EN

Stack Overflow用户

发布于 2015-07-17 19:55:18

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

代码语言:javascript
复制
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

代码语言:javascript
复制
 <TextBox Extension:FocusExtension.IsFocused="{Binding IsProviderSearchFocused}"/>
票数 2
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31483650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档