How to limit WPF DataGridTextColum Text max length to 10 characters
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}}">