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";
}
}
When you decorate a method with the
RelayCommandAttribute
, anICommand
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":