在类中传递INotify属性,以便更改传播回来

时间:2012-08-15 11:46:56

标签: c# .net wpf

我实现了一个负责异步加载对象的类,并负责相应地更改游标,即在 UpdateCursor 方法中:

    static Cursor cursor;

    public AsyncLoader(Func<CbT> request, Callback callback, Cursor cursor)
    {
        this.request = request;
        this.callback = callback;
        AsyncLoader<CbT>.cursor = cursor;

        LatestRequestId = Guid.NewGuid();
        UpdateCursor();
        ...
    }

    void UpdateCursor()
    {
        if (LatestRequestId == Guid.Empty)
        {
            cursor = Cursors.Arrow;
        }
        else
        {
            cursor = Cursors.AppStarting;
        }
    }

在我要使用这个类的类中,我有Cursor属性,它实现了INotifyProperty并且它绑定到了窗口的游标:

    private Cursor _CurrentCursor;
    public Cursor CurrentCursor
    {
        get { return _CurrentCursor; }
        set
        {
            if (value != _CurrentCursor)
            {
                _CurrentCursor = value;
                OnPropertyChanged("CurrentCursor");
            }
        }
    }

在视图中:

    Cursor="{Binding CurrentCursor}"

问题是,如何将CurrentCursor传递给AsyncLoader,以便在UpdateCursor运行时,更改将反映回CurrentCursor并触发PopertyChange事件?

1 个答案:

答案 0 :(得分:0)

其中一个解决方案是创建一个接口

interface ICursorHolder{
    Cursor CurrentCursor{get;set;}
}

将类型ICursorHolder的实例传递给AsyncLoader并使用Cursor属性在类中实现此接口

public AsyncLoader(Func<CbT> request, Callback callback, ICursorHolder cursorHolder)
{
    this.request = request;
    this.callback = callback;
    AsyncLoader<CbT>.cursorHolder = cursorHolder;//change according to your logic

    LatestRequestId = Guid.NewGuid();
    UpdateCursor();
    ...
}

void UpdateCursor()
{
    if (LatestRequestId == Guid.Empty)
    {
        cursorHolder.Cursor = Cursors.Arrow;
    }
    else
    {
        cursorHolder.Cursor = Cursors.AppStarting;
    }
}

和你的班级

public class ShellPresenter: PresenterBase, ICursorHolder{   
    private Cursor _CurrentCursor;
    public Cursor CurrentCursor
    {
        get { return _CurrentCursor; }
        set {
            if (value != _CurrentCursor){
                _CurrentCursor = value;
                OnPropertyChanged("CurrentCursor");
            }
        }
    }    
}

<强> Upd1

更新了示例代码

<强> UPD2

private void CallAsync(){
   ShellPresenter shell=GetInstance();
   Loader.AsyncLoader(request,callback, shell);

}