更新时间:2023-02-26 13:44:07
我没有时间在新项目中设置您的所有代码,但我确实注意到了一个潜在问题.尝试更改 UnitInput
控件中的 Binding
:
I haven't got time to setup all of your code in a new project, but I did notice a potential problem. Try changing your Binding
s in your UnitInput
control:
<UserControl x:Class="ValidatorTest.UnitInput"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" >
<Grid DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UnitInput}}}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Label}" VerticalAlignment="Center" Width="100"/>
<TextBox Grid.Column="1" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" Text="{Binding Value, Mode=TwoWay}" HorizontalContentAlignment="Right" VerticalAlignment="Top" Width="80" Margin="5"/>
</Grid>
</UserControl>
区别在于这一行:
<Grid DataContext="{Binding RelativeSource={RelativeSource
AncestorType={x:Type UnitInput}}}">
要使用的正确 AncestorType
值是 您的 UserControl
(UnitInput
) 的名称/类型,而不是标准的 UserControl
因为没有在其中声明 Label
或 Value
属性.您可能会在 Visual Studio 的输出窗口中遇到一个错误,类似于下面的错误,当您遇到数据绑定问题时,它应该总是成为您查看的第一个位置.
The correct AncestorType
value to use is the name/type of your UserControl
(UnitInput
), not the standard UserControl
because that has no Label
or Value
properties declared in it. You would have had an error, similar to the one below, in the Output Window in Visual Studio, which should always be the first place that you look when you have data binding problems.
System.Windows.Data 错误:40:BindingExpression 路径错误:在对象"用户控件"(HashCode=55649279)上找不到标签"属性.BindingExpression:Path=Label;...
System.Windows.Data Error: 40 : BindingExpression path error: 'Label' property not found on 'object' ''UserControl' (HashCode=55649279)'. BindingExpression:Path=Label;...
请注意,您可能还有其他错误……这只是我看到的第一个错误.
Note that you may have further errors... this was just the first one that I saw.