Search code examples
c#wpfxamlicommandcommandparameter

Pass typeof as parameter to a command from xaml


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();
}

Solution

  • 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.