使用 Caliburn 寫程 Windows Phone App,通常 ViewModel 與 View 是一對一的對應。但對於一些習慣寫網頁的人來說,會覺得 Model 應該要能對應到不同的 View,例如某些頁面,運作的邏輯是相同的,只是因為不同的客製化需求,而需要不同的介面。或者是說,利用 Attribute 來指定對應的 View,而不是透過預設的規則。

在 Caliburn中,是可以透過增加額外的規則來達到前述的目的。首先新增下列 Attribute:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class ViewAttribute : Attribute
{
    public object Context { get; set; }

    public Type ViewType { get; private set; }

    public ViewAttribute(Type viewType)
    {
        ViewType = viewType;
    }
}

ViewAttribute 是用來指定 ViewModel 所對應到的 View,而它的參數有 ViewType 及 Context,一般的情況下,指定 ViewType就可以了。

 

接下來在 App.cs 中的 Configure 方法,加入下列的程式碼:

var baseLocate = ViewLocator.LocateTypeForModelType;
ViewLocator.LocateTypeForModelType = (modelType, displayLocation, context) => {
    var attribute = modelType.GetTypeInfo().GetCustomAttributes(typeof(ViewAttribute), false).OfType<ViewAttribute>().FirstOrDefault();
    return attribute != null ? attribute.ViewType : baseLocate(modelType, displayLocation, context);
};

上面的程式碼,是檢查 ViewModel 是否有使用 ViewAttribute,如果有,就回傳指定的型別,如果沒有,就呼叫預設的 LocateTypeForModelType。當然也可以使用自己的設定檔來指定 View 與 ViewModel 對應的關係。

 

最後,在 ViewModel 套上 ViewAttribute 即可。

[View(typeof(ViewAttributePage2))]
public class ViewAttributePageViewModel : ViewModelBase

arrow
arrow
    全站熱搜

    卑微研究生 發表在 痞客邦 留言(0) 人氣()