新增一个自定义控件继承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