My project uses CommunityToolkit.Mvvm
8.0.
I use the [RelayCommand]
attributeto create a method to generate the command.
https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/generators/overview
Why is Click
working fine but OnSelectionChanged
not working?
Code:
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Text="{Binding FirstName}"/>
<Button Content="Click Me" Command="{Binding OnSelectionChangedCommand}"/>
<Button Content="Click Me" Command="{Binding ClickCommand}"/>
</StackPanel>
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
public partial class ViewModel : ObservableObject
{
[ObservableProperty]
private string firstName = "Kevin";
public ViewModel()
{
}
[RelayCommand]
private void OnSelectionChanged()
{
FirstName = "David";
}
[RelayCommand]
private void Click()
{
FirstName = "David";
}
}
CodePudding user response:
According to RelayCommand attribute, "On" at the head of method name will be removed from auto-generated command.
The generator will use the method name and append "Command" at the end, and it will strip the "On" prefix, if present.
Thus, the name of Command will be SelectionChangedCommand
.
CodePudding user response:
When you decorate a method with the RelayCommandAttribute
, an ICommand
property is generated and the name of that generated property will be method name with "Command" appended at the end.
As the docs clearly says, the "On" prefix will also be stripped from the generated property name.
So your sample code works just fine if you simply remove the "On" part from the XAML markup as there is no generated command named "OnSelectionChangedCommand":
<Button Content="Click Me" Command="{Binding SelectionChangedCommand}"/>