3 回答

TA貢獻2016條經驗 獲得超9個贊
我有一個視圖模型定位器類。每個屬性都將是我將在視圖上分配的視圖模型的實例。我可以檢查代碼是否在設計模式下運行或不使用DesignerProperties.GetIsInDesignMode。這使我可以在設計時使用模擬模型,并在運行應用程序時使用真實對象。
public class ViewModelLocator
{
private DependencyObject dummy = new DependencyObject();
public IMainViewModel MainViewModel
{
get
{
if (IsInDesignMode())
{
return new MockMainViewModel();
}
return MyIoC.Container.GetExportedValue<IMainViewModel>();
}
}
// returns true if editing .xaml file in VS for example
private bool IsInDesignMode()
{
return DesignerProperties.GetIsInDesignMode(dummy);
}
}
要使用它,我可以將定位器添加到App.xaml資源中:
xmlns:core="clr-namespace:MyViewModelLocatorNamespace"
<Application.Resources>
<core:ViewModelLocator x:Key="ViewModelLocator" />
</Application.Resources>
然后將您的視圖(例如:MainView.xaml)連接到您的視圖模型:
<Window ...
DataContext="{Binding Path=MainViewModel, Source={StaticResource ViewModelLocator}}">
- 3 回答
- 0 關注
- 1123 瀏覽
添加回答
舉報