3

Im just getting to grips with databinding, Im struggling with binding to properties that are nested within an ObservableCollection further down the object, namely In a DataTemplate of a ListView I am trying to bind to the Day.DayDate property below.

Its a diary app & this is its structure (edited to keep it brief) :

public class Month : INotifyPropertyChanged
{
    public DateTime StartDate { get; set; }
    public ObservableCollection<Day> Days { get; set; }
}

public class Day : INotifyPropertyChanged
{
    public DateTime DayDate { get; set; }
    public ObservableCollection<Gig> Gigs { get; set; }
}

public class Gig : INotifyPropertyChanged
{
    // Properties of a gig
}

I initially populate the Months Days like this:

private void InitMonth(Month calendarMonth)
{
    // create a Day Object for each day of month, create a gig for each booking on that day (done in LoadDay)
    int daysInMonth = DateTime.DaysInMonth(calendarMonth.StartDate.Year, calendarMonth.StartDate.Month);
    Day dc;
    for (int day_cnt = 0; day_cnt < daysInMonth; day_cnt++)
    {
        dc = new Day();
        dc.DayDate = calendarMonth.StartDate.AddDays(day_cnt);
        calendarMonth.Day.Add(dc);
    }
}

I want my Main Window to have three sections:

  1. Month ListView (showing all its Days)
  2. Day ListView (showing selected Days Gigs)
  3. Content Control (showing selected Gigs gig properties)

Im stuck on part 1, My Xaml looks like this :

<StackPanel>
  <TextBlock Text="{Binding Path=StartDate, StringFormat={}{0:MMMM}}"/>// Month Heading
  <ListView Name="lv_month"
    ItemsSource="{Binding}"
    ItemTemplate="{StaticResource dayItem}">// Each Day in Month
  </ListView>
</StackPanel>

<DataTemplate x:Key="dayItem">
  <StackPanel>
    <TextBlock Text="{Binding Path=Day.DayDate, StringFormat={}{0:dd ddd}}" />
  </StackPanel>
</DataTemplate>

In the TextBlock, Binding to the Months StartDate works fine, then I want to show all the Months Day Objects DayDate (upto 31, ie 01 Sat through to 31 Mon) listed underneath.

Its not showing Day.DayDate! How do I bind to it?

You can see at the moment 'Path=Day.DayDate' but I have tried just about every possibility which leads me to believe im approaching this from the wrong angle.

Any help greatly appreciated

tinmac
  • 2,357
  • 3
  • 25
  • 41

1 Answers1

5

Your ItemsSource of the ListView of your Month template needs to bind to Days:

Change

ItemsSource="{Binding}"

to

ItemsSource="{Binding Days}"

Secondly, consider each template as handling that object, so change this:

<TextBlock Text="{Binding Path=Day.DayDate, StringFormat={}{0:dd ddd}}" />

To

<TextBlock Text="{Binding Path=DayDate, StringFormat={}{0:dd ddd}}" />

And it should work! ;)

Arcturus
  • 26,677
  • 10
  • 92
  • 107
  • Great! That did it, thanks so much, so {Binding Days} is the equivalent to {Binding Path=Days} - The object in the Month Object I wish to bind to, I get it now. – tinmac Jul 07 '11 at 14:06