天天看點

Caliburn.Micro學習筆記(五)----協同IResult

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

作者:李鵬

出處:http://www.cnblogs.com/li-peng/

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。

繼續閱讀