c# - 接受来自按钮的命令参数到 DelegateCommand

标签 c# wpf xaml visual-studio-2015 prism

我有一个项目控件,我将一个可观察的对象集合传递给它,并将元素显示为按钮。我正在使用 DelegateCommands 捕获 View 模型中的按钮单击。

我想知道如何知道点击了哪个按钮。我希望能够将与按钮关联的对象传递到我的 VM。

我的 xaml:

<ItemsControl x:Name="list" ItemsSource="{Binding ChemList}"> //ChemList is observable collection of objects
    <ItemsControl.ItemTemplate>
        <DataTemplate>
             <Button Margin="5" 
                     Command="{Binding ElementName=list,Path=DataContext.OnBtnSelect}"
                     CommandParameter="{Binding}">
                <Button.Content>
                   <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding name}"/>
                        <TextBlock Text="    "/>
                        <TextBlock Text="{Binding num}"/>
                   </StackPanel>
                </Button.Content>
            </Button>
        </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>

我的 View 模型:

public DelegateCommand OnBtnSelect { get; private set; }


In the constructor:
OnBtnSelect = new DelegateCommand(OnSelect);


public void OnSelect()
{
      //How do i get here the object associated with the clicked button? 
}

最佳答案

public DelegateCommand<object> OnBtnSelect { get; private set; }

public void OnSelect(object args)
{
    //If your binding is correct args should contains the payload of the event
}

//In the constructor
OnBtnSelect = new DelegateCommand<object>(OnSelect);

关于c# - 接受来自按钮的命令参数到 DelegateCommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43638223/

相关文章:

wpf - 无法将属性 '[attr]' 中的值转换为类型 'System.Windows.TemplateBindingExtension' 的对象

c# - Metro 8 - 绑定(bind) ListView 导致 System.ArgumentException "Value does not fall within the expected range"

c# - 为什么这个翻译动画不起作用?

c# - CSVReader - CSV 文件中不存在字段

c# - 了解是否尚未在 XAML 中设置 DependencyProperty

c# - 获取空对象的父类(C# 反射)

c# - WPF 数据网格 : DataGridCheckBoxColumn events

c# - 使用大文档时运行正则表达式非常慢

c# - 如何避免 WPF 验证中的错误图标与其他元素重叠

c# - 中断后如何连续滚动到scrollviewer MVVM的底部