xamarin / XamarinCommunityToolkit

The Xamarin Community Toolkit is a collection of Animations, Behaviors, Converters, and Effects for mobile development with Xamarin.Forms. It simplifies and demonstrates common developer tasks building iOS, Android, and UWP apps with Xamarin.Forms.
MIT License
1.58k stars 471 forks source link

[Bug] TabView does not allow to change BindingContext #981

Open SeRgI1982 opened 3 years ago

SeRgI1982 commented 3 years ago

Description

Because TabViewItem content can be heavy and it can be related with very thick ViewModel, I would like to delegate (separate) this data management to another ViewModel's which are injected into my MainPageViewModel.

Steps to Reproduce

  1. Create Page with TabView and a few TabViewItem's
  2. Create ViewModel for that Page with property referenced to another ViewModel
  3. Bind BindingContext of TabViewItem.Content to this another ViewModel

Expected Behavior

TabViewItem.Content.BindingContext points to property in visible in XAML

Actual Behavior

TabViewItem.Content.BindingContext automatically switch to main Page ViewModel

Basic Information

Sample app below:

Steps:

  1. Run sample app,
  2. Click Button
  3. TabViewItem's with indexes 1, 2, 3, 4 have content with BindingContext bounded to AnotherViewModel
  4. Take a look on Label "BindingContextType" <- is different than what we have in XAML. Why ?

TabViewTest.zip

j-fritsch commented 3 years ago

Unfortunately, it looks like every time the binding context of the TabView changes, it sets each of the TabViewItems to the same BindingContext as the TabView.

https://github.com/xamarin/XamarinCommunityToolkit/blob/main/src/CommunityToolkit/Xamarin.CommunityToolkit/Views/TabView/TabView.shared.cs#L430

Kapusch commented 3 years ago

I also have this requirement, and I have been able to find a workaround.

Initially, I was assigning BindingContext property directly in my MainView XAML file, for each TabViewItem component:

    <xct:TabView>
            <xct:TabViewItem>
                <view:TabView1 x:Name="TabView1" BindingContext = "{Binding TabView1ViewModel}"/>
            </xct:TabViewItem>
            <xct:TabViewItem>
                <view:TabView2 x:Name="TabView2" BindingContext = "{Binding TabView2ViewModel}"/>
            </xct:TabViewItem>
            <xct:TabViewItem>
                <view:TabView3 x:Name="TabView3" BindingContext = "{Binding TabView3ViewModel}"/>
            </xct:TabViewItem>
        </xct:TabView>

But instead, I assign BindingContext property for each in "OnAppearing" method of my MainView:

protected override void OnAppearing()
        {
            TabView1.BindingContext = (this.BindingContext as MainViewModel).TabView1ViewModel;
            TabView2.BindingContext = (this.BindingContext as MainViewModel).TabView2ViewModel;
            TabView3.BindingContext = (this.BindingContext as MainViewModel).TabView3ViewModel;
    }
Elifas-TeQ commented 1 year ago

I am experiencing the same issue.