ItemsControl 内按钮的 WPF 命令参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19217325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:47:47  来源:igfitidea点击:

WPF Command Parameter for button inside ItemsControl

wpfmvvm

提问by erelo

I am developing a WPF application using the MVVM design pattern. In the application I have an ItemsControl that display several Buttons (number of buttons is not constant, according the logic flow of the application). The ItemsControl is binded to LinkedList in the ViewModel. I am able to define a Command for the Buttons and I able to get the Command handler within the ViewModel only if the Command has no parameters... I need to be able to know which button has been clicked and therefore I would like to have a Command with Parameter.

我正在使用 MVVM 设计模式开发 WPF 应用程序。在应用程序中,我有一个 ItemsControl 显示几个按钮(根据应用程序的逻辑流程,按钮的数量不是恒定的)。ItemsControl 绑定到 ViewModel 中的 LinkedList。我能够为按钮定义一个命令,并且只有当命令没有参数时,我才能在 ViewModel 中获取命令处理程序......我需要能够知道哪个按钮被点击,因此我想要带参数的命令。

How do I need to define my View ? What is the Syntax for the CommandParameter and which parameter I can used to get the Button content ? What will be the Command signature in the ViewModel ?

我需要如何定义我的 View ?CommandParameter 的语法是什么,我可以使用哪个参数来获取 Button 内容?ViewModel 中的 Command 签名是什么?

Please note that I am using RelayCommand from MVVM Light. The relvant code of the View is here. Thanks in advance

请注意,我使用的是来自 MVVM Light 的 RelayCommand。视图的相关代码在这里。提前致谢

<UserControl x:Class="Museum.Controls.CategoriesView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="130" d:DesignWidth="418">
    <UserControl.Resources>
        <DataTemplate x:Key="CategoriesButtonsTemplate">
            <Button Content="{Binding }" 
                    Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, Path=DataContext.CategorySelectedCommand}" 
                    />
        </DataTemplate>
    </UserControl.Resources>
    <Grid ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition Height="50"></RowDefinition>
            <RowDefinition Height=" 40"></RowDefinition>
            <RowDefinition Height=" 40"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid x:Name="SubSubjectGrid" Grid.Row="0"></Grid>
        <Grid x:Name="CategoriesGrid" Grid.Row="1">
            <ItemsControl Grid.Row="1" 
                  ItemsSource="{Binding Path=CategoriesButtons}" 
                  ItemTemplate="{StaticResource CategoriesButtonsTemplate}" >
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal"  HorizontalAlignment="Stretch"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
     </Grid>
        <Grid x:Name="SelectedCategoryGrid" Grid.Row="2"></Grid>
    </Grid>  
</UserControl>

回答by Mohd Ahmed

You can simply use CommandParameter="{Binding }" like this

您可以像这样简单地使用 CommandParameter="{Binding }"

       <DataTemplate x:Key="CategoriesButtonsTemplate">
        <Button Content="{Binding }" 
                Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, Path=DataContext.CategorySelectedCommand}" 
                CommandParameter="{Binding }" 
                />
    </DataTemplate>

回答by Tobias Hoefer

There is a generic RelayCommand class in MVVM Light toolkit which can handle command parameters. The non generic RelayCommand class ignores them. Here is a example:

MVVM Light 工具包中有一个通用的 RelayCommand 类,可以处理命令参数。非通用 RelayCommand 类会忽略它们。下面是一个例子:

First bind your CommandParameter property like Ahmed showed in his answer:

首先绑定你的 CommandParameter 属性,就像 Ahmed 在他的回答中显示的那样:

    <Button Content="{Binding}" 
            Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, Path=DataContext.CategorySelectedCommand}" 
            CommandParameter="{Binding}" />

Lets say the linked list for the buttons in your viewmodel is a list of strings. Your button content and your CommandParameter are bound to one of your list items. Now create a generic RelayCommand propterty in your viewmodel:

假设视图模型中按钮的链接列表是一个字符串列表。您的按钮内容和您的 CommandParameter 绑定到您的列表项之一。现在在你的视图模型中创建一个通用的 RelayCommand 属性:

 private RelayCommand<String> mOnClickCommand;

 public RelayCommand<String> ClickCommand
 {
     get { return mOnClickCommand; }         
 }

Instantiate it for example like this in your constructor:

例如,在您的构造函数中实例化它:

 mOnClickCommand = new RelayCommand<string>(OnButtonClicked);

And finally in your method you will get the CommandParameter property as a method argument:

最后在您的方法中,您将获得 CommandParameter 属性作为方法参数:

 private void OnButtonClicked(String _category)
 {
     Console.WriteLine(_category);
 }

Hope this is helpful.

希望这是有帮助的。

回答by Sasha

You can use Interactivity and Iteractions libraries. In this case your should add this to your xaml code of a button:

您可以使用交互和迭代库。在这种情况下,您应该将其添加到按钮的 xaml 代码中:

<Button>
  <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
              <ei:CallMethodAction TargetObject="{Binding}" MethodName="OnClick"/>
        </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>

And to viewModel:

并查看模型:

public void OnClick(object sender, MouseEventArgs args)
{// your code }