David Brunelle
David Brunelle

Reputation: 6440

Set a Maximum length to a DataGridTextBoxColumn in WPF

Is there a way to set the maximum length in a DataGridTextBoxColumn in WPF ? I can't find this property and the only way I can think is by using a DataGridTemplateColumn.

However, when I do, I get some other problems when trying to edit. I'de like to have the same behavior : The text is selected and I can start typing right way, which is not what I get now.

thanks

Upvotes: 2

Views: 1524

Answers (1)

Camilo Martinez
Camilo Martinez

Reputation: 1803

I know this one is a bit old but I reached it before the answer of a similar question, so just for reference purposes.

You can use the EditingElementStyle property where you can target the inner TextBox of the cell.

<DataGridTextColumn>
    <DataGridTextColumn.EditingElementStyle>
        <Style TargetType="TextBox">
            <Setter Property="MaxLength" Value="10"/>
        </Style>
    </DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>

If you have this in several places you can move this style to a common resource or to a separate file and use it from there. In this case you need something like:

Style resource:

<Style TargetType="{x:Type TextBox}" x:Key="TextBoxWithMaxLength" >
    <Setter Property="MaxLength" Value="10"/>
</Style>

XAML:

<DataGridTextColumn EditingElementStyle="{StaticResource TextBoxWithMaxLength}"/>

Upvotes: 3

Related Questions