I can not get MVVM to work

73 views Asked by At

I am desperately trying to implement MVVM and for some reason it is not working. I am using MVVM light on a Windows 8.1 Store App.

What am I doing wrong? I followed three tutorials by now and nothing seems to work..

I retrieve the Data from a Webservice and that part 100% works just fine. The ObservableCollection contains data.

The rest of my code looks like this:

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>();
    }
}

ViewModel:

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"); } }
}

Code Behind:

public MainPage()
{
    this.InitializeComponent();
    WeatherViewModel vm = new WeatherViewModel();
    vm.GetAllWeatherData();
}

View:

...
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>
1

There are 1 answers

0
DrewCan On

I'm not sure but there are a couple things that seem suspect to me. Initially you set your DataContext property. Are your sure your DataContext is what you're expecting after this assignment? You can set a breakpoint in your view's constructor after you call InitializeComponent to check.

Further in your ItemsSource binding you're saying "Weather.WeatherData" sourced by your locator. This seems redundant and maybe wrong. Maybe just try "WeatherData" and remove the Source specification. If your DataContext is a Weather, then that will be the object used for all bindings in that xaml file.