Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Tab from TabControl in WPF without violating the MVVM pattern

My WPF Windows contains a TabControl which displays content on different tabs. A click on the button below executes a method via ICommand interface / Binding. The called method generates text which is intended to be displayed in the second tab.

Application Mockup

How can I switch to the second tab on button click without violating the MVVM Pattern?

I tried to bind the TabItem.IsSelected Property to something in my ViewModel but I wanted to use the other tabs (tab1) as well.

Any thoughts?

like image 266
Joel Avatar asked Mar 06 '13 16:03

Joel


2 Answers

I found it out by myself.

The key is a two way binding. When the button is clicked it sets the property DisplayXamlTab true. The IsSelected attribute is bound to this variable. if another tab is clicked the binding will set the DisplayXamlTab Property to false.

Note: UpdateSourceTrigger=PropertyChanged is also very important

Code comes below:

XAML:

        <TabItem Header="XAML" IsSelected="{Binding DisplayXamlTab, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
            <Grid Background="#FFE5E5E5">
                <TextBox x:Name="TxtXamlOutput" IsReadOnly="True" Text="{Binding XamlText, Mode=TwoWay, NotifyOnTargetUpdated=True, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" AcceptsReturn="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible"/>
            </Grid>
        </TabItem>

C# Property:

private bool displayXamlTab;
public bool DisplayXamlTab
{
    get { return this.displayXamlTab; }
    set
    {
        this.displayXamlTab = value;
        this.RaisePropertyChanged("DisplayXamlTab");
    }
}
like image 72
Joel Avatar answered Nov 05 '22 22:11

Joel


if you're going the MVVM way you're going to create two dependency properties in the code behind:

  • ObservableCollection<ItemType> Items;
  • ItemType MySelectedItem;

Then, bind the TabControl ItemsSource property to the Items and bind the SelectedItem property to MySelectedItem

    <TabControl ItemsSource="{Binding Items}"
        SelectedItem="{Binding MySelectedItem, Mode=TwoWay}">
<TabControl.ItemTemplate>
    <DataTemplate>
        <... here goes the UI to display ItemType ... >
    </DataTemplate>
  </TabControl.ItemTemplate>
</TabControl>

When you want to change the selected tab, simply update the MySelectedItem dependecy property

like image 12
sim1 Avatar answered Nov 05 '22 20:11

sim1