C
C#12mo ago
mario12136

❔ Attributes for commands: implementing "feature search"

Background: So I have worked on a simple text editor app and have a MainViewModel full of commands that I bind to menu items. I wanted to see if I can create something like Feature Search in Visual Studio or think command palette like vscode if you will. That's when I stumbled upon this amazing concept called attributes. I want to see if this is a good way to achieve what I want. I create an attribute like this
[AttributeUsage(AttributeTargets.Property)]
public class CommandInfoAttribute : Attribute
{
public string Description { get; }

public CommandInfoAttribute(string description)
{
Description = description;
}
}
[AttributeUsage(AttributeTargets.Property)]
public class CommandInfoAttribute : Attribute
{
public string Description { get; }

public CommandInfoAttribute(string description)
{
Description = description;
}
}
and in my MainViewModel I add this to my commands:
[RelayCommand]
[property: CommandInfo("New File")]
private async Task NewFileAsync()
{
...
}
[RelayCommand]
[property: CommandInfo("New File")]
private async Task NewFileAsync()
{
...
}
and then, using reflection, I would find all public IRelayCommands defined in my mainviewmodel and get their descriptions along with any other attributes, for example what MenuItem they are defined for ("File > New File"). That data I can feed to my search control that will display a list of commands and once clicked used the .Execute() method of said command. Perhaps I can create a model that takes my MainViewModel and returns this command information (haven't thought this one completely through). I was wondering if this is this best or even a good way to go on about this. I wanted to achieve this with minimal changes to my existing codebase and this is what I could come up with.
2 Replies
Tvde1
Tvde112mo ago
I would say attributes like this is a fine way 👍 it means to add a new command, you just make a new class and put on the right attributes, you don't have to update any other files
Accord
Accord12mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.