如何在 WPF 中设置组合框的最大长度? [英] How to set maxlength for combobox in WPF?

查看:26
本文介绍了如何在 WPF 中设置组合框的最大长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 maxlength 设置为组合框,该组合框应用了样式.

How do i set maxlength to combobox, which is having a style applied to it.

谢谢

推荐答案

使用 DependencyProperty 时,我们可以在不修改样式/模板的情况下设置组合框的最大长度.

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 中设置组合框的最大长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆