Reputation: 13
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 ??
Upvotes: 1
Views: 129
Reputation: 169270
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.
Upvotes: 0