【发布时间】:2017-06-16 22:19:18
【问题描述】:
我不太清楚 wpf 中的验证规则是如何工作的。看来我错过了很多。我正在关注有关对文本框进行“需要文本框”验证的教程。
本教程已在 xaml 上完成。但是,我在后面的代码(C#)中创建了动态文本框。
在 Xaml 中我添加了以下资源
<UserControl.Resources>
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="25" Text="*" DockPanel.Dock="Right"></TextBlock>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
<Style x:Key="InputControlErrors" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
另外,我添加了验证类
public class RequiredFiedValidationRule : ValidationRule {
public RequiredFiedValidationRule() {
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo) {
if (value.ToString().Length > 0) {
return new ValidationResult(true, null);
}
else {
return new ValidationResult(false, "Required Field Validation");
}
}
}
在我的这部分代码中,我在 for 循环中生成文本框。本教程在 Xaml 中完成了所有绑定,在创建每个 TextBox 期间,我尝试在我的代码中做同样的事情。代码运行时没有错误,但在验证部分没有结果(它仍然接受空值)。注意:这只是for循环中的一部分代码,我删除了不重要的部分。
foreach (Department department in Departments) {
TextBox textBox = new TextBox();
textBox.Name = "Department" + department.Id.ToString();
textBox.Width = 70;
textBox.MaxWidth = 70;
textBox.HorizontalAlignment = HorizontalAlignment.Center;
textBox.VerticalAlignment = VerticalAlignment.Center;
Grid.SetColumn(textBox, 1);
Grid.SetRow(textBox, row);
//me trying to attache the validation rule with no luck :(
Validation.SetErrorTemplate(textBox, this.FindResource("validationTemplate") as ControlTemplate);
textBox.Style= this.FindResource("InputControlErrors") as Style;
Binding binding = new Binding();
binding.Source = this;
binding.Path = new PropertyPath(textBox.Name);
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
RequiredFiedValidationRule textBoxRequiredRule = new RequiredFiedValidationRule();
binding.ValidationRules.Add(textBoxRequiredRule);
BindingOperations.SetBinding(textBox, TextBox.TextProperty, binding);
NCRGrid.Children.Add(textBox);
}
}
老实说,我不确定自己在验证部分做了什么,我只是想让它发挥作用。
【问题讨论】: