我有這樣創造了一個驗證規則:如何將其他數據傳遞到ValidationRule?
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.");
}
}
}
的依賴對象定義爲:
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>
...
無論出於什麼原因,我似乎無法環繞我的大腦,Tag pro TagDependencyObject上的perty不會被設置爲null。我試着操作綁定模式,UpdateSourceTrigger,似乎沒有任何工作。我知道一個事實,即我的ViewModel上的屬性被填充,因爲窗口上的其他組件正在適當地運行。我還驗證了ViewModel屬性在運行ValidationRule之前已經設置好了。我究竟做錯了什麼?
我故意用這種方式表達了我所做的這個問題,因爲也許有更好的方式來做我想做的事情,我不知道,所以我願意接受替代方案。我的最終目標是在上面的XAML中列出的TextBox上提供驗證,但我需要的不僅僅是TextBox中的文本來進行實際驗證(只是Tag類的幾個屬性)。
我基本上遵循以下網站上描述的內容。
你應該使用這個轉換器。 –
ValidationRule舊。你的目標是什麼.Net版本? – Shoe
我在這個項目中使用了4。轉換器如何提供驗證? – MGSoto