Open xunmeng2002 opened 2 years ago
`
<TabItem Header="Order2" DataContext="{Binding ElementName=mainWindow}">
<DataGrid ItemsSource="{Binding ElementName=mainWindow, Path=OrderViewModel.Orders}" AutoGenerateColumns="False" IsReadOnly="True">
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding isSelected, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="False">
<DataGridCheckBoxColumn.Header>
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:MainWindow}, Path=OrderViewModel.IsAllOrderSelected, UpdateSourceTrigger=PropertyChanged}">SelectAll</CheckBox>
</DataGridCheckBoxColumn.Header>
</DataGridCheckBoxColumn>
</DataGrid.Columns>
</DataGrid>
</TabItem>
`
@xunmeng2002 Please update the issue with the required details in the template. Also share a minimal repro project, rather than just the xaml.
Thanks for your reply, I found the solution separately. However, the pages other than the first TabItem of the TabControl control behave differently when binding data. The code for uploading the demo project here is not very readable. Let me provide a Github address, and I will upload the code there. DemoForTabControlBindingError
@xunmeng2002 What solution did you find and how do they behave differently?
My solution is to specify the DataContext field of that CheckBox in the constructor of MainWindow.
That solution effectively hides the bug you found. RelativeSource
binding is indeed broken in .NET 5 and later, and it's quite bizarre that there aren't more reports about this.
Some changes in the framework somehow imply that DataContext is set to null and used - causing the binding error. E.g.:
dotnet --info
)winver
)Security issues and bugs should be reported privately, learn more via our responsible disclosure guidelines.
Problem description: Binding Error on the second TabItem. I use a DataGrid in a TabControl, and under the two TabItems below the TabControl, add two identical DataGrids. The DataGrid under the first TabItem binds data successfully, but the CheckBox for the header of the first column under the second DataGrid fails.
Actual behavior:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='BindingTest.MainWindow', AncestorLevel='1''. BindingExpression:Path=OrderViewModel.IsAllOrderSelected; DataItem=null; target element is 'CheckBox' (Name=''); target property is 'IsChecked' (type 'Nullable`1')
Expected behavior:
Minimal repro: `
`