如何在WPF中设置组合框的maxlength? [英] How to set maxlength for combobox in WPF?
本文介绍了如何在WPF中设置组合框的maxlength?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将maxlength设置为应用了样式的组合框。
How do i set maxlength to combobox, which is having a style applied to it.
感谢
推荐答案
使用DependencyProperty时,我们可以设置组合框的maxlength,而不修改样式/模板。
When Using DependencyProperty, we can set the maxlength of the combo box without modifying your style/template.
public class EditableComboBox
{
public static int GetMaxLength(DependencyObject obj)
{
return (int)obj.GetValue(MaxLengthProperty);
}
public static void SetMaxLength(DependencyObject obj, int value)
{
obj.SetValue(MaxLengthProperty, value);
}
// Using a DependencyProperty as the backing store for MaxLength. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MaxLengthProperty = DependencyProperty.RegisterAttached("MaxLength", typeof(int), typeof(EditableComboBox), new UIPropertyMetadata(OnMaxLenghtChanged));
private static void OnMaxLenghtChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
var comboBox = obj as ComboBox;
if (comboBox == null) return;
comboBox.Loaded +=
(s, e) =>
{
var textBox = comboBox.FindChild(typeof(TextBox), "PART_EditableTextBox");
if (textBox == null) return;
textBox.SetValue(TextBox.MaxLengthProperty, args.NewValue);
};
}
}
使用示例:
<ComboBox ComboboxHelper:EditableComboBox.MaxLength="50" />
其中ComboboxHelper为:
Where ComboboxHelper is:
xmlns:ComboboxHelper =clr- namespace:yourNameSpace ; assembly = yourAssembly
xmlns:ComboboxHelper="clr-namespace:yourNameSpace;assembly=yourAssembly"
comboBox.FindChild(...)方法已发布此处。
这篇关于如何在WPF中设置组合框的maxlength?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文