How do i set maxlength to combobox, which is having a style applied to it.
Thanks
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.
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;
}
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With