我试图根据我们(键入的)数据库表中的最大字段长度来限制我们的 WPF 应用程序中文本条目的长度。该应用程序使用数据集并使用 ODP.NET 连接到 Oracle 数据库。
为了更好的可维护性并为我们节省大量工作,我们希望将所有 TextBox 控件的 MaxLength 绑定到 DataSet 中指定的当前表对应列中的 MaxLength。
在我们的案例中实现这种行为的最有效方法是什么?
我有完全相同的要求,这就是我想出的:
将 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 部分。