SOF*_*ser 6 validation silverlight silverlight-4.0
我在SL4中有控制权.我想要点击按钮进行数据验证.大问题通常是SL4使用绑定属性进行验证.
比如本例中给出的示例
<TextBox Text="{Binding Name,Mode=TwoWay,ValidatesOnDataErrors=true}"
Height="23"
Width="120"
HorizontalAlignment="Left"
VerticalAlignment="Top" />
Run Code Online (Sandbox Code Playgroud)
但我想表现出像这样的错误信息....

使用我自己的代码,如按钮单击我检查(textbox1.text == null)然后将此样式的错误设置为textbox1
推迟验证的一种方法是UpdateSourceTrigger=Explicit在绑定中设置属性.如果这样做,绑定将不会更新源对象,因此不会导致验证错误,直到您明确告诉绑定这样做.单击按钮时,会强制更新绑定,对每个控件使用如下所示的行:
someTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
Run Code Online (Sandbox Code Playgroud)
然后,您的属性设置器会抛出无效数据的异常.
如果有很多控件强制绑定更新,这种方法可能会有点痛苦.
此外,强制更新绑定必须在控件的代码隐藏中完成.如果您正在使用带有按钮的Command,那么您可能会遇到问题.按钮可以同时具有Command和Click事件处理程序,并且两者都将在单击按钮时执行,但我不知道发生这种情况的顺序,或者即使订单可以得到保证.一个快速的实验表明事件处理程序是在命令之前执行的,但我不知道这是否是未定义的行为.因此,在更新绑定之前,可能会触发该命令.
编程式创建验证工具提示的方法是绑定文本框的另一个属性,然后故意使用此绑定导致错误.
'sapient' 发布了一个完整的解决方案,包括 Silverlight论坛上的代码(搜索日期为07-08-2009 4:56 PM的帖子).简而言之,他/她使用一个属性创建一个辅助对象,该属性的getter抛出异常,将Tag文本框的属性绑定到此帮助程序对象,然后强制更新绑定.
'sapient的代码是在Silverlight 4发布之前编写的.我们将'他/她的代码'升级到Silverlight 4.该类ControlValidationHelper成为以下内容:
public class ControlValidationHelper : IDataErrorInfo
{
public string Message { get; set; }
public object ValidationError { get; set; }
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get { return Message; }
}
}
Run Code Online (Sandbox Code Playgroud)
很容易敲出一个快速的演示应用程序来试试这个.我创建了以下三个控件:
<TextBox x:Name="tbx" Text="{Binding Path=Text, ValidatesOnDataErrors=True, NotifyOnValidationError=True, Mode=TwoWay}" />
<Button Click="ForceError_Click">Force error</Button>
<Button Click="ClearError_Click">Clear error</Button>
Run Code Online (Sandbox Code Playgroud)
这Text两个按钮的属性和事件处理程序位于代码隐藏中,如下所示:
public string Text { get; set; }
private void ForceError_Click(object sender, RoutedEventArgs e)
{
var helper = new ControlValidationHelper() { Message = "oh no!" };
tbx.SetBinding(Control.TagProperty, new Binding("ValidationError")
{
Mode = BindingMode.TwoWay,
NotifyOnValidationError = true,
ValidatesOnDataErrors = true,
UpdateSourceTrigger = UpdateSourceTrigger.Explicit,
Source = helper
});
tbx.GetBindingExpression(Control.TagProperty).UpdateSource();
}
private void ClearError_Click(object sender, RoutedEventArgs e)
{
BindingExpression b = tbx.GetBindingExpression(Control.TagProperty);
if (b != null)
{
((ControlValidationHelper)b.DataItem).Message = null;
b.UpdateSource();
}
}
Run Code Online (Sandbox Code Playgroud)
"强制错误"按钮应该会在文本框中显示验证错误,"清除错误"按钮应该会使其消失.
如果您使用ValidationSummary,则会出现此方法的一个潜在缺点.ValidationSummary将列出所有验证错误,ValidationError而不是每个属性的名称.