将typeof作为参数传递到XAML中的命令

4

我正在构建一个应用程序,其中包含一个RibbonWindow和一个TabCollection。

每个RibbonButton都有一个命令来打开特定UserControl的选项卡。每个命令都执行相同的操作,只是打开具有不同UserControl的选项卡。有没有一种好的方法将该UserControl类型传递给称为OpenTabCommand的命令?

现在看起来是这样的:

Xaml ...

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

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

视图模型

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

使用命令参数,也许对您有所帮助:https://dev59.com/e0_Ta4cB1Zd3GeqPDsW0 和 https://dev59.com/7GPVa4cB1Zd3GeqP5m5t - Ric
1个回答

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

要确保你的RelayCommand在处理程序时接受一个参数。


对于那些想要传递系统类型的人,可以在xaml顶部添加 xmlns:system="clr-namespace:System;assembly=mscorlib",然后就可以传递 CommandParameter="{x:Type system:Int32}" - Zachary Canann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接