我拼命想要实现MVVM,但出于某种原因,它无法正常工作。我在Windows 8.1 Store App上使用MVVM灯。
我做错了什么?我现在遵循了三个教程,似乎没有任何工作......
我从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:
<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>
答案 0 :(得分:0)
我不确定,但有几件事似乎让我怀疑。最初设置DataContext属性。您确定您的DataContext是您在此作业后期望的吗?在调用InitializeComponent进行检查后,可以在视图的构造函数中设置断点。
此外,在您的ItemsSource绑定中,您说&#34; Weather.WeatherData&#34;由您的定位器提供。这似乎是多余的,也许是错误的也许只是试试&#34; WeatherData&#34;并删除源规范。如果您的DataContext是Weather,那么它将是该xaml文件中所有绑定所使用的对象。