Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit WPF DataGridTextColum Text max length to 10 characters

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.

like image 787
neo Avatar asked Sep 26 '13 13:09

neo


2 Answers

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>
like image 166
dkozl Avatar answered Oct 18 '22 16:10

dkozl


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}}">
like image 1
mpn275 Avatar answered Oct 18 '22 17:10

mpn275