【问题标题】:How to limit WPF DataGridTextColum Text max length to 10 characters如何将 WPF DataGridTextColum 文本最大长度限制为 10 个字符
【发布时间】:2013-10-02 11:29:08
【问题描述】:

如何将 WPF DataGridTextColumn 文本限制为 10 个字符的最大长度。

我不想使用DatagridTemplateColumn,因为它存在内存泄漏问题。

该字段也绑定到数据实体模型。

【问题讨论】:

  • 您的original question 接受的解决方案有什么问题以及您在说什么内存泄漏
  • 字段的值未保存在实体数据模型中。由于从 Grid 到 Context 的绑定没有发生...我还读到 DatagridtemplateColumn 有一些内存泄漏问题...!!!

标签: c# wpf c#-4.0 wpfdatagrid


【解决方案1】:

如果您不想使用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>

【讨论】:

  • 文本块的使用方法
【解决方案2】:

我知道我在挖坟,但我想出了另一种解决方案,我在其他任何地方都没有找到。它涉及使用价值转换器。有点hacky,是的,但它的优点是它不会用很多行污染xaml,如果你想将它应用于很多列,这可能很有用。

以下转换器可以完成这项工作。只需在Application.Resources 下添加对App.xaml 的以下引用:&lt;con:StringLengthLimiter x:Key="StringLengthLimiter"/&gt;,其中conApp.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 "";
            }

        }
    }

然后像这样在 xaml 绑定中引用转换器:

<DataGridTextColumn Binding="{Binding Path=SellingPrice,
UpdateSourceTrigger=PropertyChanged, 
Converter={StaticResource StringLengthLimiter}}">

【讨论】:

  • 3位数后不按多余的位数?
猜你喜欢
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-20
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
相关资源
最近更新 更多