如何将 WPF DataGridTextColum 文本最大长度限制为 10 个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19029204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to limit WPF DataGridTextColum Text max length to 10 characters
提问by neo
How can I limit WPF DataGridTextColumnText to max length of 10 characters.
如何将 WPFDataGridTextColumn文本限制为 10 个字符的最大长度。
I don't want to use DatagridTemplateColumn, because it has memory leak problems.
我不想使用DatagridTemplateColumn,因为它有内存泄漏问题。
Also the field is bound to a data entity model.
该字段还绑定到数据实体模型。
回答by dkozl
If you don't want to use DatagridTemplateColumnthen you can change DataGridTextColumn.EditingElementStyleand set TextBox.MaxLengththere:
如果您不想使用,DatagridTemplateColumn则可以DataGridTextColumn.EditingElementStyle在TextBox.MaxLength那里更改和设置:
<DataGridTextColumn Binding="{Binding Path=SellingPrice, UpdateSourceTrigger=PropertyChanged}">
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="{x:Type TextBox}">
<Setter Property="MaxLength" Value="10"/>
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>
回答by mpn275
I know I'm gravedigging a bit, but I came up with another solution to this that I didn't find anywhere else. It involves the use of a value converter. A bit hacky, yes, but it has the advantage that it doesn't pollute the xaml with many lines, which might be useful, if you want to apply this to many columns.
我知道我在挖坟,但我想出了另一种解决方案,我在其他任何地方都找不到。它涉及使用值转换器。有点hacky,是的,但它的优点是它不会用多行污染xaml,如果您想将其应用于多列,这可能很有用。
The following converter does the job. Just add the following reference to App.xamlunder Application.Resources: <con:StringLengthLimiter x:Key="StringLengthLimiter"/>, where conis the path to the converter in App.xaml.
以下转换器可以完成这项工作。只需App.xaml在Application.Resources:下添加以下引用<con:StringLengthLimiter x:Key="StringLengthLimiter"/>,其中con转换器的路径在哪里App.xaml。
public class StringLengthLimiter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if(value!=null)
{
return value.ToString();
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int strLimit = 3;
try
{
string strVal = value.ToString();
if(strVal.Length > strLimit)
{
return strVal.Substring(0, strLimit);
}
else
{
return strVal;
}
}
catch
{
return "";
}
}
}
Then just reference the converter in xaml binding like this:
然后像这样在 xaml 绑定中引用转换器:
<DataGridTextColumn Binding="{Binding Path=SellingPrice,
UpdateSourceTrigger=PropertyChanged,
Converter={StaticResource StringLengthLimiter}}">

