我有DataGrid,它有一列要根据属性显示/隐藏。我在显示/隐藏列方面没有运气,所以我们最终将列取出并放入单独的 DataGrid 中,并将第二个 DataGrid 放在扩展器中。第二个 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')
当扩展器随后展开时,绑定不会更新并继续"中断"。
问题:即使最初未扩展扩展器,如何使绑定正确绑定?
刚刚找到了一种绑定我的列 (http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/) 可见性的方法,但是这重新引入了与扩展器相同的问题。但易于修复,只需对标题内容使用与可见性相同的绑定即可。