【问题标题】:MaxLength in WPF TextBox from Column property in DataSet来自 DataSet 中 Column 属性的 WPF TextBox 中的 MaxLength
【发布时间】:2011-04-14 14:43:48
【问题描述】:
我正在尝试根据我们(键入的)数据库表中的最大字段长度来限制 WPF 应用程序中文本条目的长度。该应用程序使用 DataSet 并使用 ODP.NET 连接到 Oracle 数据库。
为了更好的可维护性并节省大量工作,我们希望将所有 TextBox 控件的 MaxLength 绑定到 DataSet 中指定的当前表对应列中的 MaxLength。
在我们的案例中,实现此类行为的最有效方法是什么?
【问题讨论】:
标签:
wpf
binding
textbox
dataset
maxlength
【解决方案1】:
我有完全相同的要求,这就是我想出的:
将 MaxLength 作为属性存储在 VM 中,然后通过列的 EditingElementStyle 设置单元格的 MaxLength 属性(前提是它的类型为 DataGridTextBoxColumn):
在您的虚拟机中:
private static readonly DependencyProperty MaxLengthProperty = TextBox.MaxLengthProperty.AddOwner(typeof(MyCellVM));
internal int MaxLength
{
get { return (int)(GetValue(MaxLengthProperty)); }
set { SetValue(MaxLengthProperty, value); }
}
然后在列的构造函数中:
EditingElementStyle = new Style(typeof(TextBox));
EditingElementStyle.Setters.Add(new Setter(TextBox.MaxLengthProperty, new Binding(source + "MaxLength") { Mode = BindingMode.OneWay }));
注意:我必须像这样在列的构造函数中设置源变量:
string source = String.Format(CultureInfo.InvariantCulture, "[{0}].", dataGrid.Columns.Count);
这样做只是因为我在运行时填充了dataGrid的column,我事先不知道会有多少,但是如果你有一个固定的结构,这对你来说更容易,你应该可以为了适应,您甚至应该能够将此代码放入 xaml 部分。