【发布时间】:2015-06-18 19:47:34
【问题描述】:
我正在拼命尝试实现 MVVM,但由于某种原因它无法正常工作。我在 Windows 8.1 Store App 上使用 MVVM light。
我做错了什么?到目前为止,我遵循了三个教程,但似乎没有任何效果..
我从 Web 服务中检索数据,这部分 100% 工作得很好。 ObservableCollection 包含数据。
我的其余代码如下所示:
ViewModelLocator:
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
// Create design time view services and models
SimpleIoc.Default.Register<IDesignTimeWeatherServiceLayer, DesignTimeWeatherServiceLayer>();
}
else
{
// Create run time view services and models
SimpleIoc.Default.Register<IWeatherServiceLayer, WeatherServiceLayer>();
}
SimpleIoc.Default.Register<WeatherViewModel>();
}
public WeatherViewModel Weather
{
get
{
return ServiceLocator.Current.GetInstance<WeatherViewModel>();
}
}
视图模型:
public class WeatherViewModel : ViewModelBase
{
WeatherServiceLayer serviceLayer = new WeatherServiceLayer();
public async void GetAllWeatherData()
{
WeatherData = await serviceLayer.GetAllWeatherAsync();
}
private ObservableCollection<Weather> weatherData;
public ObservableCollection<Weather> WeatherData { get { return weatherData; } set { weatherData = value; RaisePropertyChanged("WeatherData"); } }
}
代码背后:
public MainPage()
{
this.InitializeComponent();
WeatherViewModel vm = new WeatherViewModel();
vm.GetAllWeatherData();
}
查看:
...
DataContext="{Binding Weather, Source={StaticResource Locator}}">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<GridView ItemTemplate="{StaticResource WeatherItemTemplate}" ItemsSource="{Binding Weather.WeatherData, Source={StaticResource Locator}}"/>
</Grid>
数据模板:
<DataTemplate x:Key="WeatherItemTemplate">
<StackPanel>
<TextBlock Text="{Binding Temperature}" Height="60" Margin="15,0,15,0"/>
<TextBlock Text="{Binding WeekDay}" Margin="15,0,15,10"/>
</StackPanel>
</DataTemplate>
【问题讨论】:
-
虽然您已经提供了很多关于您正在做什么的详细信息,但它可以通过更好地描述“它不工作”的含义来帮助您获得答案。当您运行应用程序时实际发生了什么与您预期会发生什么?
-
这不是您使用 MVVM Light 设置数据上下文的方式。要么使用视图模型定位器(需要将其设置为资源),要么在后面的代码中创建视图模型并在那里分配数据上下文。
-
感谢您的反馈。当我启动应用程序时,我希望数据显示在我的 GridView 中。相反,我什么也没看到。
-
你后面的代码没有意义。如果您使用 viewmodellocator,则应在 app.xaml 中将其设置为应用程序数据源,然后将数据上下文设置为天气属性。尝试在你的类构造函数中设置一些断点,看看调用了什么。
-
小心在您的构造函数和设计时视图中访问数据 - 它会在不断重建时大大减慢您的设计器。
标签: c# mvvm winrt-xaml mvvm-light