首页 > 其他分享 >wpf combobox 去除下拉框展开时自动选择文本

wpf combobox 去除下拉框展开时自动选择文本

时间:2024-10-15 18:49:02浏览次数:11  
标签:combobox CaretIndex private element SelectionLength wpf txt 下拉框

新增一个自定义控件继承ComboBox,同事在输入事件之前打开下拉框

 public partial class ComboBoxEx : ComboBox
 {
     public ComboBoxEx()
     {
     }
     private int caretPosition;

     public override void OnApplyTemplate()
     {
         base.OnApplyTemplate();

         var element = GetTemplateChild("PART_EditableTextBox");
         if (element != null)
         {
             var textBox = (TextBox)element;
             //};
             textBox.SelectionChanged += OnDropSelectionChanged;
         }
     }

     private void OnDropSelectionChanged(object sender, System.Windows.RoutedEventArgs e)
     {
         TextBox txt = (TextBox)sender;

         Trace.WriteLine("Selection changed: " + txt.SelectionLength + ",CaretIndex:" + txt.CaretIndex);

         if (base.IsDropDownOpen && txt.SelectionLength > 0)
         {
             txt.CaretIndex = caretPosition;
         }
         if (txt.SelectionLength == 0 && txt.CaretIndex != 0)
         {
             caretPosition = txt.CaretIndex;
         }

         e.Handled = true;
     }
 }

前台

  <usercontrolsex:ComboBoxEx IsTextSearchEnabled="False" IsEditable="True"  FontSize="15"
         x:Name="txtUser"  PreviewTextInput="txtUser_PreviewTextInput"/>

后台事件

    private void txtUser_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        txtUser.IsDropDownOpen = true;
    }

标签:combobox,CaretIndex,private,element,SelectionLength,wpf,txt,下拉框
From: https://www.cnblogs.com/ives/p/18468167

相关文章

  • WPFDeveloper正式版发布
    WPFDeveloperWPFDeveloper一个基于WPF自定义高级控件的WPF开发人员UI库,它提供了众多的自定义控件。该项目的创建者和主要维护者是现役微软MVP闫驚鏵:https://github.com/yanjinhuagood该项目还有众多的维护者,详情可以访问github上的README,项目地址:https://github.com/WPFDeve......
  • WPF中MVVM的应用举例
    WPF(WindowsPresentationFoundation)是微软开发的用于创建用户界面的框架,而MVVM(Model-View-ViewModel)模式是一种分离前端UI逻辑与后台业务逻辑的方法。在WPF中使用MVVM模式可以提高代码的可维护性、可测试性和可扩展性。在这篇文章中,我们将深入探讨WPF中的MVVM模式,并通过具......