| title | author | description | keywords | dev_langs | |
|---|---|---|---|---|---|
RelayCommand |
Sergio0694 |
A command whose sole purpose is to relay its functionality to other objects by invoking delegates |
windows 10, uwp, windows community toolkit, uwp community toolkit, uwp toolkit, mvvm, componentmodel, property changed, notification, binding, command, delegate, net core, net standard |
|
The RelayCommand and RelayCommand<T> are ICommand implementations that can expose a method or delegate to the view. These types act as a way to bind commands between the viewmodel and UI elements.
Platform APIs:
RelayCommand,RelayCommand<T>,IRelayCommand,IRelayCommand<T>
RelayCommand and RelayCommand<T> have the following main features:
- They provide a base implementation of the
ICommandinterface. - They also implement the
IRelayCommand(andIRelayCommand<T>) interface, which exposes aNotifyCanExecuteChangedmethod to raise theCanExecuteChangedevent. - They expose constructors taking delegates like
ActionandFunc<T>, which allow the wrapping of standard methods and lambda expressions.
The following shows how to set up a simple command:
public class MyViewModel : ObservableObject
{
public MyViewModel()
{
IncrementCounterCommand = new RelayCommand(IncrementCounter);
}
private int counter;
public int Counter
{
get => counter;
private set => SetProperty(ref counter, value);
}
public ICommand IncrementCounterCommand { get; }
private void IncrementCounter() => Counter++;
}And the relative UI could then be (using WinUI XAML):
<Page
x:Class="MyApp.Views.MyPage"
xmlns:viewModels="using:MyApp.ViewModels">
<Page.DataContext>
<viewModels:MyViewModel x:Name="ViewModel"/>
</Page.DataContext>
<StackPanel Spacing="8">
<TextBlock Text="{x:Bind ViewModel.Counter, Mode=OneWay}"/>
<Button
Content="Click me!"
Command="{x:Bind ViewModel.IncrementCounterCommand}"/>
</StackPanel>
</Page>The Button binds to the ICommand in the viewmodel, which wraps the private IncrementCounter method. The TextBlock displays the value of the Counter property and is updated every time the property value changes.
- Check out the sample app (for multiple UI frameworks) to see the MVVM Toolkit in action.
- You can also find more examples in the unit tests.