This post告訴你如何爲暴露你的自定義命令創建動態性能。您可以將其與反射混合以處理大量命令。
創建一個自定義屬性:
[AttributeUsage(AttributeTargets.Class)]
public class CommandClassAttribute : Attribute
{
readonly string commandName;
public CommandClassAttribute(string commandName)
{
this.commandName = commandName;
}
public string CommandName
{
get { return commandName; }
}
}
然後標記它所有的命令:
[CommandClass("New")]
public class NewCommand : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
MessageBox.Show("New");
}
public event EventHandler CanExecuteChanged;
}
然後,您可以加載所有的命令在應用程序啓動:
readonly Dictionary<string, ICommand> commands = new Dictionary<string, ICommand>();
void LoadCommands()
{
Type[] types = Assembly.GetExecutingAssembly().GetExportedTypes();
var iCommandInterface = typeof(ICommand);
foreach (Type type in types)
{
object[] attributes = type.GetCustomAttributes(typeof(CommandClassAttribute), false);
if (attributes.Length == 0) continue;
if (iCommandInterface.IsAssignableFrom(type))
{
string commandName = ((CommandClassAttribute)attributes[0]).CommandName;
commands.Add(commandName, (ICommand)Activator.CreateInstance(type));
}
}
}
這種架構可以輕鬆擴展以支持插件中的定義命令。
當我有很多命令時,我已經將它們放置在名爲XXXXCommanding的虛擬機的部分類中,其中XXXX是VM的名稱。然而,我不會把它們放在收藏中。如果我需要迭代所有命令,我將使用反射。 –
你是否認爲你的ViewModels可能會做很多工作? – CodeMonkey
我在@CodeMonkey上。濫用部分類來跨越多個單獨文件分裂你的巨人類只是隱藏了問題。 –