Caliburn.Micro學習筆記目錄
今天說一下協同IResult
看一下IResult接口
/// <summary> /// Allows custom code to execute after the return of a action. /// </summary> public interface IResult { /// <summary> /// Executes the result using the specified context. /// </summary> /// <param name="context">The context.</param> void Execute(ActionExecutionContext context); /// <summary> /// Occurs when execution has completed. /// </summary> event EventHandler<ResultCompletionEventArgs> Completed; }Execute方法里寫你要執行的事件,在最后執行事件Completed這是一定要執行的,不然會無法執行后繼的yield部分
Execute 方法有一個ActionExecutionContext參數,這個參數與建立UI相關的IResult實現中
非常有用。它能提供的功能如下
public class ActionExecutionContext{ public ActionMessage Message; public FrameworkElement Source; public object EventArgs; public object Target; public DependencyObject View; public MethodInfo Method; public Func<bool> CanExecute; public object this[string key];}Message: 造成這 IResult 的調用原始 ActionMessage。
Source: FrameworkElement 觸發執行的行動。
EventArgs: 與行動的觸發器相關聯的任何事件參數。
Target: 在實際的操作方法存在的類實例。
View: 與目標關聯的視圖。
Method: MethodInfo 指定要在目標實例上調用的方法。
CanExecute: 一個函數,如果操作可被調用、 虛假否則返回 true。
key index: 一個地方來存儲/檢索它可以對框架的擴展所使用的任何附加元數據。
做一個小Demo
源碼:CaliburnIresult.rar
由于這個例子很簡單我們把bootstrapper也寫簡單一些
class HelloBootstrapper : Bootstrapper<MyViewModel> { }這樣就可以 了新建一下Loader類去實現IResult接口
public class Loader : IResult { readonly string _str; public Loader(string str) { _str = str; } public void Execute(ActionExecutionContext context) { MessageBox.Show(_str + context.View); Completed(this, new ResultCompletionEventArgs());//這個方法一定要加到這里,這個方法完成后才會執行后邊的方法 } public event EventHandler<ResultCompletionEventArgs> Completed = (sender, args) => { MessageBox.Show(((Loader)sender)._str ); }; }前臺我們就放一下button就可以
<Window x:Class="CaliburnIresult.MyView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/PResentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:cal="http://www.caliburnproject.org" Title="MyView" Height="300" Width="300"> <Grid> <Button Content="IResult" cal:Message.Attach="MyIResultClick"/> </Grid></Window>在ViewModel里我們看一下它的方法實現
public IEnumerable<IResult> MyIResultClick() { yield return new Loader("load....."); yield return new Loader("Ok!"); }源碼:CaliburnIresult.rar
新聞熱點
疑難解答