MaxLength in WPF TextBox from Column property in DataSet
I'm trying to limit the length of text entries in our WPF application according to the maximum field length in our (typed) Database tables. The application employs DataSets and connects to an Oracle database using ODP.NET.
For better maintanability and to save us from a lot of work we'd like to bind the MaxLength of all TextBox controls to the MaxLength in the current table's corresponding column that is spec开发者_如何学JAVAified in the DataSet.
What is the most efficient way to implement such behaviour in our case?
I had exactly the same requirement and this is what I came up with:
store the MaxLength as a property in your VM and then set the cell's MaxLength property through the column's EditingElementStyle (providing it is of type DataGridTextBoxColumn):
in your VM:
private static readonly DependencyProperty MaxLengthProperty = TextBox.MaxLengthProperty.AddOwner(typeof(MyCellVM));
internal int MaxLength
{
get { return (int)(GetValue(MaxLengthProperty)); }
set { SetValue(MaxLengthProperty, value); }
}
then in your column's constructor:
EditingElementStyle = new Style(typeof(TextBox));
EditingElementStyle.Setters.Add(new Setter(TextBox.MaxLengthProperty, new Binding(source + "MaxLength") { Mode = BindingMode.OneWay }));
NB: I had to set the source variable in the column's constructor like this:
string source = String.Format(CultureInfo.InvariantCulture, "[{0}].", dataGrid.Columns.Count);
only did this because I'm populating the dataGrid'scolumn at runtime and I don't know in advance how many there will be, but if you have a fixed structure, this is even easier for you, you should be able to adapt, you should even be able to put this code in the xaml part.
精彩评论