4

I'm building an application which has a RibbonWindow and a TabCollection.

Every RibbonButton has a command to open a tab of a specific UserControl. Every command does the same with a very small difference, they open a tab with a specific UserControl. Is there a good way of passing that UserControl type to one command called OpenTabCommand?

This is how it looks right now:

Xaml ...

<RibbonButton Label="OpenTab1"
              LargeImageSource="/something.png" 
              Command="{Binding OpenTab1Command}" />

<RibbonButton Label="OpenTab2"
              SmallImageSource="/something.png" 
              Command="{Binding OpenTab2Command}"/>

...

ViewModel

public RelayCommand OpenTab1Command{ get; set; }

public RelayCommand OpenTab2Command { get; set; }

public MainViewModel()
{
    OpenTab1Command= new RelayCommand(OpenTab1, param => true);

    OpenTab2Command = new SearchCommand(OpenTab2, param => true);
}

private void OpenTab1()
{
    var item = new TabItem
    {
        Content = new Tab1(),
    };

    TabCollection.Add(item);

    item.Focus();
}

private void OpenTab2()
{
    var item = new TabItem
    {
        Content = new Tab2(),
    };

    TabCollection.Add(item);

    item.Focus();
}
Verendus
  • 1,026
  • 1
  • 13
  • 26
  • use the command parameter, maybe this is of use to you: http://stackoverflow.com/questions/3482343/wpf-how-to-pass-whole-control-as-commandparameter-via-xaml and http://stackoverflow.com/questions/10438564/how-to-pass-a-usercontrol-with-commandparameter – Ric Nov 12 '14 at 16:54

1 Answers1

7

You can use CommandParameter

<RibbonButton Label="OpenTab1"
              LargeImageSource="/something.png" 
              Command="{Binding OpenTab1Command}" 
              CommandParameter="{x:Type (YOUR TYPE)}"/>

and make sure your RelayCommand accepts a parameter on its handler.

123 456 789 0
  • 10,565
  • 4
  • 43
  • 72
  • For those interested in passing system types, add `xmlns:system="clr-namespace:System;assembly=mscorlib"` to the top of the xaml, then you can pass `CommandParameter="{x:Type system:Int32}"` – Zachary Canann Nov 04 '17 at 02:54