How can I limit WPF DataGridTextColumn
Text to max length of 10 characters.
I don't want to use DatagridTemplateColumn
, because it has memory leak problems.
Also the field is bound to a data entity model.
If you don't want to use DatagridTemplateColumn
then you can change DataGridTextColumn.EditingElementStyle
and set TextBox.MaxLength
there:
<DataGridTextColumn Binding="{Binding Path=SellingPrice, UpdateSourceTrigger=PropertyChanged}">
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="{x:Type TextBox}">
<Setter Property="MaxLength" Value="10"/>
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>
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.
The following converter does the job. Just add the following reference to App.xaml
under Application.Resources
: <con:StringLengthLimiter x:Key="StringLengthLimiter"/>
, where con
is the path to the converter in 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:
<DataGridTextColumn Binding="{Binding Path=SellingPrice,
UpdateSourceTrigger=PropertyChanged,
Converter={StaticResource StringLengthLimiter}}">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With