简体   繁体   中英

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:

    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. In XAML part of the SearchResultsViewModel, results are presented as Buttons dynamically. 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. Is it possible to do this without code behind ??

You could just move the command property to the Recipe class. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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