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.
How they workPlatform APIs:
RelayCommand
,RelayCommand<T>
,IRelayCommand
,IRelayCommand<T>
RelayCommand
and RelayCommand<T>
have the following main features:
ICommand
interface.IRelayCommand
(and IRelayCommand<T>
) interface, which exposes a NotifyCanExecuteChanged
method to raise the CanExecuteChanged
event.Action
and Func<T>
, which allow the wrapping of standard methods and lambda expressions.ICommand
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4