How can I set a ComboBox's entered text length?
That it would not be longer, than 20, for example.
How can I set a ComboBox's entered text length?
That it would not be longer, than 20, for example.
I used PreviewKeyDown event, very simple + you can show warning or something.
Register the method below to your ComboBox.PreviewKeyDown += event,
KeyDown event will not fire if user press Space.
private void ComboBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (ComboBox.Text.Length > 19) // allow max 20 chars
{
if (e.Key != Key.Back) // allow removing chars
{
e.Handled = true; // block any additional key press if there is more than allowed max
System.Media.SystemSounds.Beep.Play(); // optional: beep to let user know he is out of space :)
}
}
}
Just to make the story complete:
you have two options:
Combobox obviously contains TextBox
in its template. You need to find a way to access the TextBox, probably through Combobox Template
and set it's MaxLength
You probably databind Combobox.Text to a viewmodel property. You can do the validation in viewmodel using INotifyDataErrorInfo or even by throwing an exception from setter. User will see error message if he exceeds the max allowed length. I think this is better from UX perspective. Unfortunatelly it's quite a lot of work to make it work if you are not using INotifyDataErrorInfo yet.
On ComboBox Class (MSDN):
<ComboBox>
Items
</ComboBox>
The entered length depends on the items you put into it. Therefore you cannot set that property. Textboxes however do have a max length:
<TextBox MaxLength="20">
Text
</TextBox>
I found an easy solution via XAML. In ComboBox resources we can set the style for a textbox and via setter set maxlenth.
<ComboBox Name="comboBox" Width="100" IsEditable="True">
<ComboBox.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="MaxLength" Value="yourValue"/>
</Style>
</ComboBox.Resources>
</ComboBox>
EDIT: This works with Actipro ComboBox. For usual comboBox to make this work, have a look here