Eric after dark
Eric after dark

Reputation: 1808

Getting access to a Tab Control in a View Model class

I have a View Model that controls a Tree View. Also in my GUI is a Tab Control that is not controlled by the View Model. If I want to use the Tree View to access elements of the Tab Control how would I give my View Model access to it (the Tab Control)?

I'm guessing it would be something along the lines of how I pass a selected item from the Tree View from code-behind to the View Model.

Code-Behind:

//Gets selected item in TreeView
private void Tree_One_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
       MainWindowViewModel.SelectedItem = e.NewValue as TreeViewItem;
}

View Model:

public static TreeViewItem SelectedItem { get; set; } //Selected Node\

My current attempt

Code-Behind:

MainWindowViewModel.middleControl = tabControl1 as TabControl;

View Model:

public static TabControl middleControl { get; set; }

The following doesn't work because the View Model still does not see the any of the items inside the Tab Control

if (parent_Node.Items.Contains(SelectedItem))
                middleControl.SelectedIndex = nameOfTabItem;

Upvotes: 1

Views: 875

Answers (2)

Eric after dark
Eric after dark

Reputation: 1808

If you want to access view elements from other classes in the project you can query the window. When my SelectedItem changes I call to a function in my View Model that queries the window and then proceeds to perform operations.

Yes - I know this is not proper MVVM etiquette, but it works, and it provides a solution to my question.

Code-Behind:

//Gets selected item in TreeView
private void Tree_One_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
       MainWindowViewModel.SelectedItem = e.NewValue as TreeViewItem;
       MainWindowViewModel.changeTab();
}

View Model:

//Controls the changing of tabs, corresponding with the selected TreeViewItem
public static void changeTab()
{
    //Query for Window1
    var mainWindow = Application.Current.Windows
        .Cast<Window1>()
        .FirstOrDefault(window => window is Window1) as Window1;

    //Change selected tab item
    if (parent_Node.Items.Contains(SelectedItem)) 
         mainWindow.TabItem.IsSelected = true;

    //other operations....
}

Upvotes: 1

Andy
Andy

Reputation: 30418

The view model should not use the Tab control directly. The whole purpose of MVVM architecture is separation of the UI and business logic. Only the view should access the controls in the UI, and even then that is rarely necessary due to data binding and the logic in the view model.

Why is the tab control not managed by the view model?

Also the view model shouldn't know anything about TreeViewItems - it should operate on the model class that is bound to each item in the tree.

Upvotes: 1

Related Questions