Somma
Somma

Reputation: 27

Set DataGridTextColumn MaxLength property dynamically

I want to set the DataGridTextColumn.MaxLength property dynamically based on an integer variable. Therefore, in some cases it should be 4 and in others it should be 5.

I tried it with a binding on the MaxLength value like this:

<DataGridTextColumn.EditingElementStyle>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="MaxLength" Value="{Binding MaxTextBoxLength, UpdateSourceTrigger=PropertyChanged}"/>
    </Style>
</DataGridTextColumn.EditingElementStyle>
public int MaxTextBoxLength
{
    get => maxTextBoxLength;
    set
    {
        maxTextBoxLength= value;
        RaisePropertyChanged();
    }
}

Upvotes: 0

Views: 151

Answers (1)

mm8
mm8

Reputation: 169400

iF MaxTextBoxLength is defined in the view model, you could bind to it using the RelativeSource property:

<DataGridTextColumn.EditingElementStyle>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="MaxLength"
                Value="{Binding DataContext.MaxTextBoxLength, 
                    RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
    </Style>
</DataGridTextColumn.EditingElementStyle>

Upvotes: 1

Related Questions