例外が発生しないようにするには、パラメーターが null ではなく、メソッドがパラメーターを 1 つだけ受け入れる場合にのみパラメーターを追加する必要があります。
短い答えは、このチェックを追加します:
if (parameter != null)
{
action.Parameters.Add(new Parameter { Value = parameter });
}
または、元の受け入れられた回答のこの改良版を使用できます。これにより、メソッドのパラメーターに応じて、任意の数の引数または null を渡すことができます。
public static void AttachActionMessage(this DependencyObject control, string eventName, string methodName, params object[] parameters)
{
var action = new ActionMessage { MethodName = methodName };
if (parameters != null)
{
foreach (var parameter in parameters)
{
action.Parameters.Add(new Parameter { Value = parameter });
}
}
var trigger = new System.Windows.Interactivity.EventTrigger
{
EventName = eventName,
SourceObject = control
};
trigger.Actions.Add(action);
Interaction.GetTriggers(control).Add(trigger);
}
コードはこれらの方法でテストされ、機能しています。
IncrementCountButton.AttachActionMessage("Click", "IncrementCount", null);
IncrementCountButton2.AttachActionMessage("Click", "IncrementCount2", 12);
public void IncrementCount()
{
Count++;
}
public void IncrementCount2(int value)
{
Count += value;
}