Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set maxlength for combobox in WPF?

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

Thanks

like image 214
Ershad Avatar asked Oct 15 '09 14:10

Ershad


3 Answers

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.

like image 200
Tri Q Tran Avatar answered Oct 30 '22 11:10

Tri Q Tran


Or you can use the GotFocus or Loaded event of the combobox for setting the maxlength.If the maxlength doest change too much during runtime you can use loaded event or else use gotfocus event

<ComboBox Height="30" IsEditable="True" Loaded="ComboBox_Loaded"/>

and in the respective event...

   var obj = (ComboBox)sender;
    if (obj != null)
    {
        var myTextBox = (TextBox)obj.Template.FindName("PART_EditableTextBox",obj);
        if (myTextBox != null)
        {
            myTextBox.MaxLength = maxLength;
        }
    }
like image 35
biju Avatar answered Oct 30 '22 10:10

biju


You are correct. There is a maxlength for a Textbox, but not for a combobox. You have to roll your own using a Textbox as an intermediary. Here's some code:

public int MaxLength {get; set;}
protected override void OnGotFocus(System.Windows.RoutedEventArgs e)
{
    base.OnGotFocus(e);
    TextBox thisTextBox = (TextBox)base.GetTemplateChild("PART_EditableTextBox");
    if (thisTextBox != null)
        thisTextBox.MaxLength = MaxLength;
}
like image 2
Rap Avatar answered Oct 30 '22 11:10

Rap