【发布时间】:2013-11-05 01:00:16
【问题描述】:
我有一个这样创建的验证规则:
public class TagFitsConstraintRule : ValidationRule
{
public TagDependencyObject SelectedTag { get; set; }
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
Tag tag = SelectedTag.Tag;
if (tag != null)
{
if (tag.TagConstraintPattern == null)
{
return ValidationResult.ValidResult;
}
else
{
// Perform additional validation for the tag
}
}
else
{
return new ValidationResult(false, "No tag selected.");
}
}
}
Dependency 对象定义为:
public class TagDependencyObject : DependencyObject
{
public static readonly DependencyProperty TagProperty = DependencyProperty.Register("Tag", typeof(Tag), typeof(TagDependencyObject), new UIPropertyMetadata(null));
public Tag Tag
{
get { return (Tag)GetValue(TagProperty); }
set { SetValue(TagProperty, value); }
}
}
我在 XAML 中将其用作:
<Window
...>
<Window.Resources>
<d:TagDependencyObject x:Key="TagDependencyObject" Tag="{Binding CurrentlySelectedTag}"/>
</Window.Resources>
...
<TextBox ... >
<TextBox.Text>
<Binding Path="CurrentlySelectedTag" Converter="{StaticResource TagDataConverter}" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<c:TagFitsConstraintRule ValidatesOnTargetUpdated="True" SelectedTag="{StaticResource TagDependencyObject}"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
...
无论出于何种原因,我似乎无法全神贯注,TagDependencyObject 上的 Tag 属性不会因为设置为 null 而让步。我试过操纵绑定模式,UpdateSourceTrigger,似乎没有任何效果。我知道一个事实,即我的 ViewModel 上的属性已填充为窗口上的其他组件正在适当地运行。我还验证了 ViewModel 属性是在运行 ValidationRule 之前设置的。我做错了什么?
我故意用我的方式来表达这个问题,因为也许有一种更好的方法可以做我不知道的我想做的事情,所以我愿意接受替代方案。我的最终目标是在上面 XAML 中列出的 TextBox 上提供验证,但我需要的不仅仅是 TextBox 中的文本来进行实际验证(只需 Tag 类的几个属性)。
我基本上遵循以下网站上的描述。
【问题讨论】:
-
你应该为此使用转换器。
-
ValidationRule 是旧的。您的目标是什么 .Net 版本?
-
我在这个项目中使用了 4。转换器如何提供验证?