How to set maxlength for combobox in WPF?

Ershad picture Ershad · Oct 15, 2009 · Viewed 14.2k times · Source

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

Thanks

Answer

Tri Q Tran picture Tri Q Tran · Oct 21, 2009

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);
            };
    }
}

Usage example:

<ComboBox ComboboxHelper:EditableComboBox.MaxLength="50" />

Where ComboboxHelper is:

xmlns:ComboboxHelper="clr-namespace:yourNameSpace;assembly=yourAssembly"

comboBox.FindChild(...) method is posted here.