我正在尝试验证WPF中的一些输入数据,并使用DataResource代理,如下所述: http://www.wpfmentor.com/2009/01/how-to-add-binding-to-property-on.html
所以,这是我的XAML(简化):
<mvvm:BaseDataView
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:md="clr-namespace:Mfc.Mvvm.Master"
>
<mvvm:BaseDataView.Resources>
<ResourceDictionary>
<md:DataResource x:Key="mmSS" BindingTarget="{Binding ElementName=tbMmss,Path=Text}"/>
<md:DataResource x:Key="mmTS" BindingTarget="{Binding ElementName=tbMmts,Path=Text}"/>
</ResourceDictionary>
</mvvm:BaseDataView.Resources>
...
<TextBox x:Name="tbMmts" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="2" Grid.Column="1" Width="100" Margin="3,3,0,0">
<TextBox.Text>
<Binding Path="MTS" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<md:DoubleRangeValidationRule MinValue="10.0" MaxValue="5000.0"/>
<md:LessThanValidationRule>
<md:LessThanValidationRule.LessThanChecker>
<md:ProxyForComparisonString
CompareTo="{md:DataResourceBinding DataResource={StaticResource mmSS}}">
</md:ProxyForComparisonString>
</md:LessThanValidationRule.LessThanChecker>
</md:LessThanValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
...
<TextBox x:Name="tbMmss" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="3" Grid.Column="1" Width="100" Margin="3,3,0,0">
<TextBox.Text>
<Binding Path="STS" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<md:DoubleRangeValidationRule MinValue="10.0" MaxValue="5000.0"/>
<md:GreaterThanValidationRule>
<md:GreaterThanValidationRule.GreaterThanChecker>
<md:ProxyForComparisonString
CompareTo="{md:DataResourceBinding DataResource={StaticResource mmTS}}">
</md:ProxyForComparisonString>
</md:GreaterThanValidationRule.GreaterThanChecker>
</md:GreaterThanValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
验证适用于第二个文本框,但它会因第一个文本框的NullReferenceException而崩溃。 DataResource 似乎没有初始化,调试说
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=tbMmss'. BindingExpression:Path=Text; DataItem=null; target element is 'DataResource'
有什么想法吗?谢谢!
答案 0 :(得分:1)
你有一个完全错误的方法。不要使用Freezables。他们很坏。他们不会被困在资源中而违反了像桥梁这样的交易!请使用附加属性或INotifyDataError信息来正确解决此问题。