我不清楚wpf中的验证规则是如何运作的。似乎我错过了很多。我正在学习一个关于“#34;文本框是必需的"验证TextBox。
本教程已在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循环中生成Textboxes。本教程在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);
}
}
说实话,我不确定我在验证部分做了什么,我只是想让它发挥作用。
答案 0 :(得分:1)
您需要将Text
的{{1}}属性绑定到源属性才能使验证生效。
TextBox
类应该有Department
属性,我们称之为string
,Name
绑定到:{/ p>
TextBox