Different views/usercontrols on each tab of a TabControl

后端 未结 2 1979
天涯浪人
天涯浪人 2020-12-16 06:29

I\'m trying to write a program that uses tabs to hold different usercontrols. What I currently want to happen is the user clicks a find button, a new tab is created, and a f

相关标签:
2条回答
  • 2020-12-16 06:35

    I've just answered my own question.

    The tabitems that get created dynamically are set up with a datacontext of the individual item from the tabcontrols itemsource property, in this case one of my viewmodels.

    The datatemplate I used correctly picks up the correct view for the viewmodel type and displays this.

    However my view set the datacontext of the grid on the view to my resource and so nothing was showing up. I've changed this to use the datacontext instead of the resource and now everything is working.

    So my main problem was having my views run off of resources and not the datacontext. I still would prefer to use resources but as datacontext works I'm going to have to go with that.

    0 讨论(0)
  • 2020-12-16 06:36

    I would make my main ViewModel look like this:

    • ObservableCollection<ViewModelBase> OpenTabs
    • ICommand AddTabCommand
    • ICommand CloseTabCommand

    In the Constructor, a new SearchViewModel is created and added to OpenTabs, and it's Search method gets hooks up to some method in the MainViewModel

    The method in the MainViewModel that handles the Search command would create a new CustomerViewModel with the specified customer, set it's CloseCommand, and then add it to the OpenTabs

    var vm = new CustomerViewModel(customer);
    vm.CloseCommand = this.CloseTabCommand;
    OpenTabs.Add(vm);
    

    You could also use an event system such as PRISM's EventAggregator or Galasoft's Messenger to pass around AddTab/CloseTab events instead of hooking up the commands from the MainViewModel

    And of course, you'd use DataTemplates to define how each OpenTab object would get displayed in the View

    <TabControl ItemsSource="{Binding OpenTabs}">
        <TabControl.Resources>
            <DataTemplate DataType="{x:Type local:SearchViewModel}">
                <local:SearchView />
            </DataTemplate>
            <DataTemplate DataType="{x:Type local:CustomerViewModel}">
                <local:CustomerView />
            </DataTemplate>
        </TabControl.Resources>
    </TabControl>
    
    0 讨论(0)
提交回复
热议问题