我目前正在尝试将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>
<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>
<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>();
}
}
答案 0 :(得分:3)
如果ViewModelLocator
类和UserControl
位于同一项目/程序集中,您可以在ViewModelLocator
中定义合并到ResourceDictionary
中的UserControl
资源{1}}像这样:
<UserControl ...>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Global.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<UserControl.DataContext>
<Binding Path="ApplicationVM" Source="{StaticResource Locator}" />
</UserControl.DataContext>
<Grid>
</Grid>
</UserControl>
<强> Global.xaml:强>
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfControlLibrary1">
<local:ViewModelLocator x:Key="Locator" />
</ResourceDictionary>