0

Starting with the MahApps-Material mashup demo, I'm trying to use a button click event to create a new TabItem from my Views. For now, the CustomTabItem will show text bound to some property from a FancyObject (being served to the View from my FancyTabViewModel). But I've got the DataContext, dependency property or the Binding done wrong.

    public void NewTabOnClick(object sender, RoutedEventArgs e)
    {
        // create my new object from Models 
        FancyObject fo = new FancyObject();
        // create the INofify VM and pass it my object
        // the VM has a public VMFancyObject property to serve the fo
        FancyTabViewModel fvm = new FancyTabViewModel(fo);
        // create the new UserControl and set its context to the VM
        CustomTabItem newTab = new CustomTabItem() {
            Header = "New tab"
        };
        newTab.DataContext = fvm;
        MainWindowTabs.Items.Add(newTab);
    }

And in my <TabItem x:Class="MyProject.Views.CustomTabItem" there is a label so bound: <Label Content="{Binding VMFancyObject.SomeList.Count}"/>

I expect to see the default count of the List created in the FancyObject's constructor. However, after the new tab is created and added to the dragablz:TabablzControl, I just see a blank label.

I also tried <Label DataContext="{Binding Path=DataContext.FancyTabViewModel,RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}" Content="{Binding VMFancyObject.SomeList.Count}" HorizontalAlignment="Left" Margin="341,196,0,0" Foreground="Black" Background="#FF97FF02"/>

dadiletta
  • 299
  • 3
  • 17
  • Is MainWindowTabs.Items.Add(**test**); correct? It seems that this should be MainWindowTabs.Items.Add(**newTab**); – nosale Dec 30 '18 at 22:12
  • 2
    Why aren't you using ItemsSource for the TabControl tabs? You've tagged MVVM, and you're assigning a DataContext....seems only sensible that you should be using data-binding for your tab panels as well. Do this and your child tab panels will inherit the DataContext automatically without the need for any of this hacky stuff. – Mark Feldman Dec 30 '18 at 23:04
  • Thanks! I was barking up the wrong tree. Binding [TabControl to a List](https://stackoverflow.com/questions/589802/how-can-i-bind-a-list-collection-to-tabcontrol-headers-in-wpf) is the better solution. – dadiletta Dec 31 '18 at 14:10

0 Answers0