简体   繁体   English

当动态生成按钮时,如何判断该按钮已被单击? (MVVM)

[英]How to tell which Button has been clicked, when it's generated dynamically? (MVVM)

I have a SearchResultsViewModel with observable collection of recipe class and a command to show a recipe: 我有一个带有配方类的可观察集合的SearchResultsViewModel和一个显示配方的命令:

    private ObservableCollection<Recipe> _searchedRecipes;
    public ObservableCollection<Recipe> SearchedRecipes
    {
        get
        {
            return _searchedRecipes;
        }
        set
        {
            _searchedRecipes = value;
            OnPropertyChanged();
        }
    }
    #endregion

    #region Show Recipe Command

    public ICommand ShowRecipeCommand { get { return new RelayCommand(() => 
    ExecuteShowRecipeCommand()); } }

    public void ExecuteShowRecipeCommand()
    {
        _locator.Main.CurrentViewModel = new DisplayRecipeViewModel();
    }
    #endregion

Another ViewModel performs a query and passes results in the constructor of this ViewModel. 另一个ViewModel执行查询并在此ViewModel的构造函数中传递结果。 In XAML part of the SearchResultsViewModel, results are presented as Buttons dynamically. 在SearchResultsViewModel的XAML部分中,结果动态显示为Button。 Each Recipe is a Button with it's name as content: 每个配方都是一个按钮,其名称为内容:

     <StackPanel>
            <ItemsControl ItemsSource="{Binding Path = SearchedRecipes}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Button Content="{Binding Path=Name}" Command="{Binding ShowRecipeCommand}"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </StackPanel>

I want ShowRecipeCommand to create new DisplayRecipeViewModel with a View bound to it, displaying the properties of Recipe that was clicked but I don't know how to tell which Button was clicked. 我想让ShowRecipeCommand创建一个绑定了View的新DisplayRecipeViewModel,显示单击的Recipe的属性,但我不知道如何知道单击了哪个Button。 Is it possible to do this without code behind ?? 有可能没有代码吗?

You could just move the command property to the Recipe class. 您可以仅将command属性移至Recipe类。 Then each Button (or rather each data object that is represented by a Button ) has its own command and you always know which one that was clicked. 然后,每个Button (或更确切地说,由Button表示的每个数据对象)都有其自己的命令,并且您始终知道单击了哪个命令。

If the Recipe class is auto-generated by some ORM such as for example Entity Framework, you could create another partial class where you define the command property. 如果Recipe类是由某些ORM(例如,Entity Framework)自动生成的,则可以在定义command属性的地方创建另一个局部类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM