2017-10-11 13 views
1

私はレシピを表示する観察可能なレシピクラスの集合とコマンドとSearchResultsViewModelを持っている:どのボタンがクリックされたのか、どのボタンがクリックされたのか(MVVM)

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 

別のViewModelは、クエリを実行し、このビューモデルのコンストラクタに結果を渡します。 SearchResultsViewModelのXAML部分では、結果がButtonとして動的に表示されます。私はShowRecipeCommandがクリックされたレシピのプロパティを表示し、それに結合されたビューで新しいDisplayRecipeViewModelを作成したいが、私は言うにする方法 分からない

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

:各レシピには、コンテンツとして、それの名前を持つボタンですどのボタンがクリックされたかを示します。 コードなしでこれを行うことは可能ですか?

+2

'CommandParameter'経由で必要なものを渡しますか?あなたの 'RelayCommand'実装がシナリオをサポートしているかどうかは分かりませんが、最悪の場合は' ICommand'を実装するだけです。 – Maverik

+1

コマンドプロパティをRecipeクラスに移動しますか? – mm8

+0

@ mm8モデルがデータベースから生成されたときにこれを行うのはいいですか? –

答えて

0

コマンドプロパティをRecipeクラスに移動するだけで済みます。次に、それぞれButton(またはむしろButtonで表される各データオブジェクト)には独自のコマンドがあり、クリックされたデータは常にわかります。

Recipeクラスが、たとえばEntity Frameworkなどの一部のORMによって自動生成される場合、コマンドプロパティを定義する別の部分クラスを作成できます。

関連する問題