![](/img/trans.png)
[英]Using Caliburn.Micro with Mahapps MetroTabItem not loading View to ContentControl
[英]Caliburn.Micro rebind ContentControl on navigation GoBack
我在WinRT應用程序中使用Caliburn.Micro
這是我的主要VM:
public class MainViewModel : Conductor<Screen>
{
protected override void OnActivate()
{
if (ActiveItem == null)
{
ActivateItem(
ViewModelLocator.LocateForViewType(typeof(NewsFeedView)) as Screen);
}
base.OnActivate();
}
}
這里我使用指揮因為我想在ContentControl中加載不同的控件,但現在我只有這個代碼。 這是我在主視圖中的內容控件:
<ContentControl x:Name="ActiveItem" Grid.Column="1" Grid.Row="1" />
當我運行應用程序時,一切正常, MainViewModel.Activate
被調用, ActiveItem
設置為NewsFeedViewModel
, ContentControl
加載NewsFeedView
。
問題:
當我使用NavigationService.NavigateToViewModel
方法在NewsFeedView
控件中NavigationService.NavigateToViewModel
到另一個視圖然后在該視圖中使用NavigationService.GoBack
,我將返回MainView
,當MainViewModel.Activate
被調用時, ActiveItem
不為null
,但ContentControl.Content
是null
。 我已經嘗試過為ContentControl
使用View.Model
附加屬性,但沒有運氣,如何重新綁定?
編輯:最后我在Caliburn設置記錄器,看看會發生什么,我發現一個錯誤 - 當導航后加載MainView這個事件發生時:
Attaching ***.Views.MainView to ***.ViewModels.MainViewModel.
ViewModel bound on ActiveItem.
Using cached view for ***.ViewModels.NewsFeedViewModel.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Exception: Unspecified error
at Windows.UI.Xaml.Controls.ContentControl.put_Content(Object value)
... some winRT stack
at Caliburn.Micro.View.SetContentPropertyCore(...
雖然它不是那么有用,我已經使用InteliTrace獲取更多信息並得到了這樣的信息:“元素已經是另一個元素的孩子了”。 我認為NewsFeedView存儲在某個地方,當時間到了將它放入ContentControl這個異常時拋出。 怎么解決這個?
您應該采用視圖模型的第一種方法。 換句話說,激活視圖模型的實例,Caliburn.Micro將為您執行視圖位置和綁定。
看起來你只想在構造函數中實例化一次視圖模型,例如OnInitialise
:
public MainViewModel()
{
this.ActivateItem(new NewsFeedViewModel());
}
正如@devdigital所說,可能只在構造函數中初始化新聞訂閱源視圖模型一次,為什么不使用Conductor.Collection.OneActive,因為在任何給定時間只有一個活動項,它用於這種情況,這可以解決你的問題問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.