C#C
C#2y ago
stigzler

✅ How to use IRelayCommand in CommunityToolkit.Mvvm with parameters?

I'm just learning WPF and also the community toolkit. I can get RelayCommands working OK if they're parameter-less, but struggling to implement a command bound to a Toggle Button to toggle a bool property on a databound control. My working approach to simple commands:

public IRelayCommand LogOutCMD { get; set; }
private void SetupCommands() // this is called at startup
{
    LogOutCMD = new RelayCommand(LogOut);
}
private void LogOut()
{
  // does stuff
}

However, I have tried something similar for the ToggleButton:
public bool CodeNumberingVisible { get => codeNumberingVisible; set => SetProperty(ref codeNumberingVisible, value); }
public IRelayCommand SetCodeNumberingVisibleCMD { get; set; }
SetCodeNumberingVisibleCMD = new RelayCommand<bool>(SetCodeNumberingVisible);
private void SetCodeNumberingVisible(bool visible)
{
    CodeNumberingVisible = visible;
}

The button and control xaml:
<ToggleButton x:Name="CodeNumberVisibleBT" ToolTip="Toggle Code Numbers"
                Command="{Binding SetCodeNumberingVisibleCMD}"
                 IsChecked="{Binding CodeNumberingVisible}"
                 CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Self}}"/>
<syncfusion:EditControl ShowLineNumber="{Binding CodeNumberingVisible}"/>


However, this renders the button inoperable (no rollover highlighting, command doesn't execute) - it works without the Command Binding.

Any ideas?

EDIT: I've just realised that I don't technically need a Command here, I can just bind the ToggleButton's IsChecked property to the property directly. However, I'm still intersted to know why the above broke the ToggleButton and how to send parameters via cmmands using the Community Toolkit.
Was this page helpful?