SamDevx
SamDevx

Reputation: 2378

Why is ItemsControl in the following WPF XAML not showing anything?

When I run the app, I expect to see 5 buttons (see ItemsControl\DataTemplate\Button in my XAML below) each with a content like "55/42" denoting max ad min temperature. However, the window is blank. I know this has to do with ItemsControl because I can display the data without using the ItemsControl. Can someone catch my mistake?

<Window x:Class="Embed_WeatherSummaryAsItemsControl_ToMain.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    FocusManager.FocusedElement="{Binding ElementName=InputCity}"
    Title="Weather App" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="30"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>
    <TextBox x:Name="InputCity" Grid.Row="0" Width="200" Text="{Binding CityAndOptionalCountry}"></TextBox>
    <Button Grid.Row="0" Width="50" Content="Go" Margin="260,0,0,0" Command="{Binding GetWeatherReportCommand}"></Button>
    <ItemsControl Grid.Row="1" ItemsSource="{Binding WeatherForecastSummaryCollection}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding Path=MaxMinTemperature}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>          
    </ItemsControl>
</Grid>

As shown below, "WeatherForecastSummaryCollection" is a collection property on ViewModel class and "MaxMinTemperature" is a property of item in collection.

public class MainWindowViewModel : ViewModelBase
{
    ....

    private List<WeatherForecastSummary> mWeatherForecastSummaryCollection;
    public List<WeatherForecastSummary> WeatherForecastSummaryCollection
    {
        get { return mWeatherForecastSummaryCollection; }
        set
        {
            mWeatherForecastSummaryCollection = value;
            OnPropertyChanged("WeatherForecastSummaryCollection");
        }
    }
    .....
}

public class WeatherForecastSummary
{
    public string MaxMinTemperature { get; set; }
}

Thanks for helping!

Upvotes: 0

Views: 1747

Answers (1)

adityaswami89
adityaswami89

Reputation: 583

I think you are missing the DataContext here. Even if you are using the codebehind of the View, you need to write

this.DataContext = this;

or if you are using someother class as viewmodel you might want to point the datacontext to that class. Just replace "this" in the above code with your viewmodels object. In this case it would be ,

this.DataContext = new MainWindowViewModel();

Upvotes: 2

Related Questions