Home > database >  Set DataGridTextColumn MaxLength property dynamically
Set DataGridTextColumn MaxLength property dynamically

Time:03-03

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();
    }
}

CodePudding user response:

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>
  • Related