dotnet / wpf

WPF is a .NET Core UI framework for building Windows desktop applications.
MIT License
7.04k stars 1.17k forks source link

Binding Error For TabControl #6845

Open xunmeng2002 opened 2 years ago

xunmeng2002 commented 2 years ago
xunmeng2002 commented 2 years ago

`

SelectAll
<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>

`

singhashish-wpf commented 2 years ago

@xunmeng2002 Please update the issue with the required details in the template. Also share a minimal repro project, rather than just the xaml.

xunmeng2002 commented 2 years ago

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

miloush commented 2 years ago

@xunmeng2002 What solution did you find and how do they behave differently?

xunmeng2002 commented 2 years ago

HU0BSF4F5D2VDPTF%JHIZ7I

xunmeng2002 commented 2 years ago

8LR9@)O`U2@HCRC_SAFU78O $2HWMP71O3~EASSH038)(@O

xunmeng2002 commented 2 years ago

}3 6$~985@JK75AD{ HM 5J

My solution is to specify the DataContext field of that CheckBox in the constructor of MainWindow.

znakeeye commented 1 year ago

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.:

  1. DataContext is set in tab 1.
  2. Switching to tab 2.
  3. DataContext is set to null.
  4. New quirk in .NET Core: Warning produced
  5. DataContext is set for tab 2.