-协同IResult

Caliburn.Micro学习笔记(五)----协同IResult

 

今天说一下协同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

 

你可能感兴趣的:(result)