【发布时间】:2016-04-27 09:08:32
【问题描述】:
我正在使用 VS 2015 开发动态 WPF 应用程序,其中控件及其绑定是在代码隐藏中生成的。 现在我想实现一个绑定到双精度数据表列的文本框。 在该文本框的构建器类中,我尝试设置格式和 MaxLength。 这一切都很好。 Format 和 MaxLength 没问题,但是当我想输入或编辑某些东西时,就很难做到了。 客户永远不会接受这一点。 我能做什么?
这里我调用了builder类:
CreateTextbox(viewmodel, "table1", "Menge", 20, 40, 60, "#0.0000", 2, 4);
这是创建和返回 TextBox 的公共方法。
/// <summary>
/// Create and returns a textbox.
/// </summary>
/// <param name="viewmodel">The viewmodel.</param>
/// <param name="tablename">The name of the datatable.</param>
/// <param name="sourceColumn">The column to which we want to bind the textbox.</param>
/// <param name="leftPos">The left position.</param>
/// <param name="topPos">The top position.</param>
/// <param name="width">The width of the textbox.</param>
/// <param name="format">The format of the value.</param>
/// <param name="integerPositions">The integerpositions before the comma.</param>
/// <param name="decimalPlaces">The decimal places after the comma.</param>
/// <returns>Returns an object of type TextBox.</returns>
public TextBox CreateTextbox(MainViewModel viewmodel, string tablename, string sourceColumn, double leftPos, double topPos,
double width, string format="", int integerPositions=0, int decimalPlaces=0)
{
// Textbox is created.
TextBox textbox = new TextBox();
textbox.Width = width;
Canvas.SetLeft(textbox, leftPos);
Canvas.SetTop(textbox, topPos);
// Now the binding to the datasource is initialized.
Binding controlbinding = new Binding();
controlbinding.Source = viewmodel.ApplicationDataSet.Tables[tablename].DefaultView;
controlbinding.Path = new PropertyPath("[0][" + sourceColumn + "]");
if (!string.IsNullOrWhiteSpace(format))
{
controlbinding.StringFormat = format;
textbox.MaxLength = integerPositions + decimalPlaces + 1;
////controlbinding.ValidationRules = ???;
}
controlbinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
textbox.SetBinding(TextBox.TextProperty, controlbinding);
return textbox;
}
yyyy
【问题讨论】:
-
尝试查找
MaskedTextBox,Xceed库有一个相当不错的库,它非常易于使用(对开发人员和最终用户而言)。这应该涵盖您对验证/绑定/格式化用户输入的需求。 (光盘:我不隶属于 Xceed,我只是碰巧已经使用过他们的库一次)