gpt4 book ai didi

c# - WPF 绑定(bind)到 ElementName 引发 NullReferenceException

转载 作者:太空宇宙 更新时间:2023-11-03 13:12:56 24 4
gpt4 key购买 nike

我正在尝试验证 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'

有什么想法吗?谢谢!

最佳答案

您对此采取了完全错误的方法。不要使用 Freezable。他们很坏。他们不会被困在资源中并像桥梁一样被侵犯!请使用附加属性或 INotifyDataError 信息来干净且正确地解决此问题。

关于c# - WPF 绑定(bind)到 ElementName 引发 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27687199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com