MyViewModel是我能修改的類,AlertMessage類是人家封裝好的類,我不能修改。請問我要怎麼才能實現如題所述的?以下是我的代碼
public class MyViewModel
{
public MyViewModel()
{
SelectCommand = new DelegateCommand(SelectCommand_Execute); ;
}
public ICommand SelectCommand { get; set; }
protected virtual void SelectCommand_Execute()
{
}
// 我要怎麼傳遞這個回調函數,這個回調函數沒有CommandExecutingMessage
private bool Callback(ICommand myCommand)
{
return true;
}
public void DoSomething()
{
MessageBus bus = new MessageBus();
// Questions
// WithCommandLifetime方法把一個方法作為參數,同時指定了一個回調
// 注意WithCommandLifetime()方法檢查了CommandExecutingMessage類型
// 我要怎麼樣才能獲取到CommandExecutingMessage類型來使WithCommandLifetime()指定回調函數
// 我要如何構建這個調用?
bus.Warning("This is test message").WithCommandLifetime(what goes here);
}
}
public class AlertMessage
{
public AlertMessage(string msg)
{
this.Message = msg;
}
public string Message { get; set; }
public bool IsExpired(object message)
{
var result = false;
if (IsExpiredDelegate != null)
{
result = IsExpiredDelegate(message);
}
return result;
}
public Func<object, bool> IsExpiredDelegate
{
get;
set;
}
}
public class MessageBus
{
public AlertMessage Warning(string msg)
{
return new AlertMessage(msg);
}
}
public static class AlertMessageLifetimePolicies
{
public static AlertMessage WithCommandLifetime(this AlertMessage source, Func<ICommand, bool> isExpiredCallback)
{
source.IsExpiredDelegate = data =>
{
var result = false;
var asCommandExecutingMessage = (data as CommandExecutingMessage);
if (asCommandExecutingMessage != null)
{
result = isExpiredCallback(asCommandExecutingMessage.Sender);
}
return result;
};
return source;
}
}
public class CommandExecutingMessage
{
private ICommand _sender;
public CommandExecutingMessage(ICommand sender)
{
this._sender = sender;
}
new public ICommand Sender
{
get { return this._sender; }
}
}
找到答案了,調用方法如下:
public void DoSomething()
{
MessageBus bus = new MessageBus();
//assign callback method
AlertMessage alertMessage = bus.Warning("this").WithCommandLifetime((x) => Callback(SelectCommand));
CommandExecutingMessage commandExcutingMessage = new CommandExecutingMessage(SelectCommand);
//call the Callback method
alertMessage.IsExpiredDelegate(commandExcutingMessage);
}