简体   繁体   中英

Tabs Opening redundancy

Currently When I press on buttons they produce New pages and creates a new Tab at the Top. I'm trying to make a case where If the tab is already created it be redirected to the working one. May I get some tips or guidance please.

    public void Show(string name)
    {
        IGridPort tab;
        switch (name)
        {
            case "Contacts":        tab = new ContactsGridViewModel(Events); break;
            case "Businesses":      tab = new ClientGridViewModel(Events); break;
            default:                tab = new QuickLaunchViewModel(Events); break;
        }
        Events.Publish(new ShowTabEvent(tab));
    }

In my apps I typically have a base class called PageViewModel for each of the tabs on the main page and a derived class called DataPageViewModel for displaying pages that should only appear once (eg a record that's being edited). I maintain an observable collection of PageViewModel to pass as the ItemsSource into my tab control and I also maintain a dictionary of DataPageViewModel so I can look them up based on the data they are displaying:

public ObservableCollection<PageViewModel> Pages { get; private set; }
private Dictionary<string, DataPageViewModel> DataPages { get; set; }

The string that I use to key the dictionary is generally a combination of the page type and a unique identifier for the data being displayed. All that remains then is to check the dictionary before you create a page to see if another page displaying that data already exists, if it does then just set that page as the active one. Setting the active page can be done by getting the DefaultView of the ObservableCollection and calling MoveCurrentTo , but a better method in MVVM is to create a property in your model to hold the currently active page:

    private PageViewModel _CurrentPage;
    public PageViewModel CurrentPage
    {
        get { return _CurrentPage; }
        set { _CurrentPage = value; RaisePropertyChanged(() => this.CurrentPage); }
    }

Then just bind it to SelectedItem in your tab control:

    <TabControl
        ItemsSource="{Binding Pages}"
        SelectedItem="{Binding CurrentPage, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
        IsSynchronizedWithCurrentItem="True" />

The binding is two-way so if the user selects a tab then CurrentPage will be updated accordingly, and if you set CurrentPage in your ViewModel then the corresponding tab will be selected in the View.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM