动态设置 DataGridTextColumn MaxLength 属性

Set DataGridTextColumn MaxLength property dynamically

我想根据整数变量动态设置 DataGridTextColumn.MaxLength 属性。因此,在某些情况下它应该是 4,而在其他情况下它应该是 5。

我试过绑定 MaxLength 值,如下所示:

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

iF MaxTextBoxLength 在视图模型中定义,您可以使用 RelativeSource 属性:

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