首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >单击WPF可编辑的ComboBox SelectAll

单击WPF可编辑的ComboBox SelectAll
EN

Stack Overflow用户
提问于 2015-06-12 05:40:16
回答 3查看 4.4K关注 0票数 6

我已经掌握了如何在SelectAll上单击TextBox文本;我也希望对可编辑的组合框- din查找任何内容进行同样的操作。我的TextBox代码是

代码语言:javascript
复制
private void OnPreviewMouseDown(Object sender, MouseButtonEventArgs e)
{
    txtBox.SelectAll();
    txtBox.Focus();
    e.Handled = true;
}

如何对可编辑的组合框进行同样的操作?

Combox的更新代码,它为我提供了我想要的输出:

代码语言:javascript
复制
private void cboMouseDown(object sender, MouseButtonEventArgs e)
        {
            var textBox = (cbo.Template.FindName("PART_EditableTextBox", cbo) as TextBox);
            if (textBox != null)
            {
                textBox.SelectAll();
                cbo.Focus();
                e.Handled = true;
            }
        }

但是现在组合框的下拉式不起作用了,有什么建议吗?

Update-2:我尝试了PreviewMouseUp而不是PreviewMouseDown,现在下拉显示了;但是一旦单击框,然后尝试打开下拉列表,窗口就会冻结。然而,我已经做了一个工作,我已经在我的回答在下面。如果这是一个正确而安全的解决方案,我将非常感谢你的评论。

EN

回答 3

Stack Overflow用户

发布于 2015-06-12 05:44:35

使用GotFocus事件并选择如下文本

代码语言:javascript
复制
    var comboTextBoxChild = comboBox.FindChild(typeof(TextBox), "PART_EditableTextBox") as TextBox;

    comboTextBoxChild .SelectAll();

这里的组合框是您可编辑的组合框名称。

票数 6
EN

Stack Overflow用户

发布于 2015-06-15 02:58:57

我已经找到了一个可能的解决方案,并为我提供了一个可行的解决方案--如果可以的话,需要一些建议;我使用的是ComboBox的ComboBox事件:

代码语言:javascript
复制
private void cboMouseUp(object sender, MouseButtonEventArgs e)
        {
            var textBox = (cbo.Template.FindName("PART_EditableTextBox", cbo) as TextBox);
            if (textBox != null && !cbo.IsDropDownOpen)
            {
                Application.Current.Dispatcher.BeginInvoke(new Action(()=>{
                    textBox.SelectAll();
                    textBox.Focus();
                    //e.Handled = true;
                }));
            }
票数 5
EN

Stack Overflow用户

发布于 2016-10-16 14:04:23

我参加聚会有点晚了,但最近我遇到了同样的问题,在测试了几个解决方案之后,我想出了自己的解决方案(为此目的创建了自定义控件):

代码语言:javascript
复制
public class ComboBoxAutoSelect : ComboBox
{
    private TextBoxBase textBox;

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        textBox = GetTemplateChild("PART_EditableTextBox") as TextBoxBase;
    }

    protected override void OnPreviewGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
    {
        // if event is called from ComboBox itself and not from any of underlying controls
        // and if textBox is defined in control template
        if (e.OriginalSource == e.Source && textBox != null)
        {
            textBox.Focus();
            textBox.SelectAll();
            e.Handled = true;
        }
        else
        {
            base.OnPreviewGotKeyboardFocus(e);
        }
    }
}

您可以对事件执行同样的操作,但是每次都需要搜索"PART_EditableTextBox“,在这里,我们只对每个模板更改执行一次。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30795981

复制
相关文章

相似问题

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