情况 :
我目前正在尝试将 my 连接DataContext
到我的ViewModel
. 我正在使用GalaSoftMvvmLight
.
但事实是我没有.Window
因为我将把这段代码集成到另一个程序中,该程序有Window
. 所以我只有UserControl
.
问题 :
我不知道为什么,但我无法连接我DataContext
的UserControl
.
我收到这个错误{"Cannot find resource named 'Locator'. Resource names are case sensitive."}
问题 :
如何将我的 App.xaml 资源正确连接到我的 View ?如果没有它是不可能的Window
,我怎么能用这样DataContext
的东西打电话
<UserControl.DataContext>
SOMETHING TO SET DATACONTEXT WITH BINDING !
</UserControl.DataContext>
这是我的代码:
应用程序.xaml
<Application x:Class="SOMETHING.App" xmlns:vm="clr-namespace:SOMETHING.ViewModel" StartupUri="ApplicationView.xaml">
<Application.Resources>
<ResourceDictionary>
<vm:ViewModelLocator x:Key="Locator" />
</ResourceDictionary>
</Application.Resources>
</Application>
应用程序视图.xaml
<UserControl x:Class="SOMETHING.View.ApplicationView"
<!-- THIS ONE DOESN'T WORK -->
DataContext="{Binding ApplicationVM, Source={StaticResource Locator}}">
<!-- THIS ONE DOESN'T WORK IF I SET <vm:ViewModelLocator x:Key="Locator" /> IN STYLE.XAML, BUT I CAN'T USE IT IN USERCONTROL PARAMETERS (LIKE ABOVE) -->
<UserControl.Resources>
<ResourceDictionary >
<ResourceDictionary.MergedDictionaries >
<ResourceDictionary Source="Style.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<Label Content="{Binding Title}" />
</Grid>
</UserControl>
视图模型定位器
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
}
else
{
SimpleIoc.Default.Register<IDataService, DataService>();
}
SimpleIoc.Default.Register<ApplicationViewModel>();
}
public ApplicationViewModel ApplicationVM
{
get { return SimpleIoc.Default.GetInstance<ApplicationViewModel>();
}
}