Come spostare il mio gestore RoutedCommand da View-codebehind a ViewModel?
-
03-07-2019 - |
Domanda
Il seguente esempio di RoutedCommand funziona.
Tuttavia, la gestione del pulsante che esegue il comando è nel codice dietro la vista . Per come capisco MVVM, dovrebbe essere nel ViewModel .
Tuttavia, quando sposto il metodo su ViewModel (e lo cambio in pubblico), viene visualizzato l'errore " ManagedCustomersView non contiene una definizione di OnSave " ;. Anche se cambio il secondo parametro di RoutedCommand in typeof (ManageCustomersViewModel), ottengo lo stesso errore.
Come posso spostare il gestore comandi da View-codebehind a ViewModel?
ManageCustomersView.xaml:
<UserControl.CommandBindings>
<CommandBinding Command="local:Commands.SaveCustomer" Executed="OnSave"/>
</UserControl.CommandBindings>
...
<Button Style="{StaticResource formButton}"
Content="Save"
Command="local:Commands.SaveCustomer"
CommandParameter="{Binding Id}"/>
ManageCustomersView.xaml.cs:
private void OnSave(object sender
, System.Windows.Input.ExecutedRoutedEventArgs e)
{
int customerId = ((int)e.Parameter);
MessageBox.Show(String.Format
("You clicked the save button for customer with id {0}.", customerId));
}
Commands.cs:
using System.Windows.Input;
using TestDynamicForm123.View;
namespace TestDynamicForm123
{
public class Commands
{
public static RoutedCommand SaveCustomer =
new RoutedCommand("SaveCustomer", typeof(ManageCustomersView));
}
}
Soluzione
Esponerai una proprietà del ViewModel che fa riferimento al comando.
class MyViewModel
{
public RoutedCommand SaveCmd{ get{ return Commands.SaveCustomer; } }
}
Quindi nella XAML
<Button Command="{Binding SaveCmd}" />
Tuttavia potresti trovare più facile usare RelayCommand in modo che puoi definire anche la logica di comando effettiva nel tuo modello.