和 RelayCommand RelayCommand<T> 是 ICommand 可公開方法或委派至檢視的實作。 這些類型可作為在 viewmodel 和 UI 元素之間系結命令的方式。
平臺 API:
RelayCommand、、、IRelayCommandRelayCommand<T>IRelayCommand<T>
運作方式
RelayCommand 和 RelayCommand<T> 具有下列主要功能:
- 它們提供介面的
ICommand基底實作。 - 它們也會實
IRelayCommand作 (和IRelayCommand<T>) 介面,其會NotifyCanExecuteChanged公開方法來引發CanExecuteChanged事件。 - 它們會公開採用 和
Func<T>等Action委派的建構函式,以允許包裝標準方法和 Lambda 表達式。
使用 ICommand
下列示範如何設定簡單的命令:
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++;
}
然後,相對UI可以是 (使用 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>
系 Button 結至 ICommand viewmodel 中的 ,它會包裝私 IncrementCounter 用方法。 會顯示 TextBlock 屬性的值 Counter ,而且會在每次屬性值變更時更新。