WPF problem with DataContext in TabControl with List as source

38 Views Asked by At

I'm having problem binding DataContext to my TabControl in WPF application, but mayby let's start from begining. Basically I want to generate tabs for each object in a list by using generic UserControl and ViewModel

In my MainWindow.xaml which itself is binded to a corresponding MainViewModel.cs I have my source of problem, that is although TabControl.ItemTemplate is binding correctly and I'm seeing correct tab name, the TabControl.ContentTemplate is not, and my question is why and what another approach should I use?:

<TabControl 
    ItemsSource="{Binding Clients}"
    SelectedItem="{Binding SelectedClient}"
    SelectedIndex="{Binding ClientViewModels.IndexOf(SelectedClientViewModel)}" >
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}" />
            
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <views:ClientGenericUserControl 
                DataContext="{Binding DataContext.ClientViewModels[SelectedIndex]}" />
            
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

in MainViewModel.cs class:

public ObservableCollection<Client>? Clients { get; set; }
public ObservableCollection<ClientGenericViewModel>? ClientViewModels { get; set; }

as for Client.cs class:

public class Client
{
    public string Name { get; set; }
    public ObservableCollection<Product> Products { get; set; }
}

as for ClientGenericViewModel.cs clss:

public class ClientGenericViewModel : BaseViewModel
{
    public Client? Client { get; set; }
    public ObservableCollection<Product>? Products { get; set; }

    private Product? _selectedProduct;

    public Product? SelectedProduct
    {
        get
        {
            return this._selectedProduct;
        }
        set
        {
            if (this._selectedProduct != value)
            {
                this._selectedProduct = value;
                NotifyPropertyChanged();
            }
        }
    }
}

In my ClientGenericUserControl.xaml for now I just want to display name:

<TextBlock 
    Text="{Binding Client.Name}" />

as I said, I'm having trouble binding DataContext in ContentTemplate. When I'm changing something in this GenericUserControl, all changes are visible so it's binding to it's corresponding ViewModel properly, but these changes are visible for all items in list. What am I missing?

0

There are 0 best solutions below