1

How can I set a ComboBox's entered text length?

That it would not be longer, than 20, for example.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sasha
  • 833
  • 1
  • 20
  • 40

4 Answers4

1

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 :)
        }
    }
}
Mr. Noob
  • 136
  • 1
  • 7
1

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.

Liero
  • 25,216
  • 29
  • 151
  • 297
0

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MrFox
  • 4,852
  • 7
  • 45
  • 81
  • Incorrect facts mentioned in the answer. Combobox has IsEditable property and when set to true, user can enter text just like in TextBox. Therefore the entered length depends on user input, not just the ComboBox's items. – Liero Sep 21 '15 at 07:38
-1

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

Sasha
  • 833
  • 1
  • 20
  • 40