I'm working with RelayCommands
(they are in a separate class) for about a month now and I got the feeling they're kind of clunky when declaring them. Below I have 3 ways I can think of how I can declare a RelayCommand
.
In a first case I declare my ICommand
and then when the ViewModel is loading I construct my RelayCommand
that points to a method in my code.
public class MyViewModel
{
public ICommand MyCommand { get; private set; }
public MyViewModel()
{
MyCommand = new RelayCommand(MyMethod, CanMyMethod);
}
private void MyMethod()
{
// Do something here ...
}
private bool CanMyMethod()
{
return string.IsNullOrEmpty(MyString) ? false : true;
}
}
A second method is to do everything at once.
public ICommand MyCommand
{
get
{
return new RelayCommand(
() =>
{
// Do something here ...
},
() =>
string.IsNullOrEmpty(MyString) ? false : true);
}
}
Now, I'm planning to write an application with quite some Commands
in a certain ViewModel. I also can't split the ViewModel in smaller ViewModels because all the controls
have to work together.
So my questions are:
- What is the best approach to declaring and constructing
ICommands
? Is it one of my approaches or is there an easier way? - How hard is it to maintain the overview with each approach considering there are over 50
ICommands
in a single ViewModel. - I'm hoping to release my application on both Windows 7, 8 and 10 in the future. Are there any limitations to
RelayCommands
I have to take in account if I'm only using .NET4.5? - Besides
RelayCommands
I also found this project: Caliburn-Micro. It allows you to do something like the code below. Does anyone have an idea how good this works performance wise in comparison toRelayCommands
? This is just an extra question and not required to be answered to have a post marked as an answer.
Xaml (View)
<Button x:Name="Login" Content="Log in" />
ViewModel
public bool CanLogin(string username, string password)
{
return !String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password);
}
public string Login(string username, string password)
{
...
}