在WPF中将最大长度设置为DataGridTextBoxColumn

时间:2012-11-22 15:09:01

标签: .net wpf maxlength

有没有办法在WPF中的DataGridTextBoxColumn中设置最大长度?我找不到这个属性,我能想到的唯一方法就是使用DataGridTemplateColumn。

然而,当我这样做时,我在尝试编辑时遇到了一些其他问题。我想要有相同的行为:文本被选中,我可以开始正确输入,这不是我现在得到的。

感谢

1 个答案:

答案 0 :(得分:2)

我知道这个有点老了但我在类似question的回答之前就达到了它,所以仅供参考。

您可以使用EditingElementStyle属性来定位单元格的内部TextBox

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

如果您在多个地方拥有此功能,则可以将此样式移动到公共资源或单独的文件,并从那里使用它。在这种情况下,您需要以下内容:

样式资源:

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

XAML:

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