我有 DataGrid,它有一个要根据属性显示/隐藏的列。我在显示/隐藏列时运气不佳,因此我们最终将列取出并将其放入单独的 DataGrid 中,并将第二个 DataGrid 放置在 Expander 中。第二个 DataGrid 的标头绑定了 Expander 的 DataContext(或 DataGrid - 效果相同,也尝试将其绑定到包含的用户控件)。
<Expander ExpandDirection="Right" Style="{DynamicResource ExpanderDirectionRight}" IsExpanded="{Binding ShowLaterDate}">
<DataGrid AutoGenerateColumns="False" AlternationCount="2" SelectionMode="Single" ItemsSource="{Binding Rows, UpdateSourceTrigger=PropertyChanged}" CanUserDeleteRows="True" CanUserAddRows="False" CanUserResizeColumns="False" SnapsToDevicePixels="True" Visibility="{Binding Rows.HasContent, Converter={StaticResource BooleanToVisibilityConverter}}" HorizontalAlignment="Left" SelectedIndex="{Binding SelectedIndex, ElementName=BudgetDataGrid}">
<DataGrid.Columns>
<DataGridTemplateColumn CellTemplate="{StaticResource LaterDataTemplate}" Width="{StaticResource WidthOfValueColumns}">
<DataGridTemplateColumn.Header>
<Grid Margin="{StaticResource MarginOfTextBox}">
<userControls:DateOrAgeEditor Date="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Expander}}, Path=DataContext.LaterDate, UpdateSourceTrigger=LostFocus}" DateOfBirth="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Expander}}, Path=DataContext.DateOfBirth}" TabIndex="11"/>
</Grid>
</DataGridTemplateColumn.Header>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Expander>
这一切都很好。
问题: 显示用户控件时显示绑定值。但仅当扩展器被扩展时!如果在显示用户控件时展开器折叠,则会打印到输出:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.Expander', AncestorLevel='1''. BindingExpression:Path=DataContext.DateOfBirth; DataItem=null; target element is 'DateOrAgeEditor' (Name='UserControl'); target property is 'DateOfBirth' (type 'DateTime')
System.Windows.Data Warning: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.Expander', AncestorLevel='1''. BindingExpression:Path=DataContext.LaterDate; DataItem=null; target element is 'DateOrAgeEditor' (Name='UserControl'); target property is 'Date' (type 'DateTime')
然后扩展扩展器时,绑定不会更新并继续“损坏”。
问题: 即使扩展器最初没有展开,如何让绑定正确绑定?