【问题标题】:Binding Path for nested objects嵌套对象的绑定路径
【发布时间】:2011-07-07 12:18:08
【问题描述】:

我刚刚开始掌握数据绑定,我正在努力绑定到嵌套在对象下方的 ObservableCollection 中的属性,即在 ListView 的 DataTemplate 中,我试图绑定到下面的 Day.DayDate 属性。

这是一个日记应用程序,这是它的结构(经过编辑以保持简短):

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
}

我最初像这样填充 Months Days:

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

我希望我的主窗口包含三个部分:

  1. 月份列表视图(显示所有天数)
  2. Day ListView(显示选定的 Days Gigs)
  3. 内容控制(显示选定的 Gigs 演出属性)

我卡在第 1 部分,我的 Xaml 看起来像这样:

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

在 TextBlock 中,绑定到 Months StartDate 工作正常,然后我想显示下面列出的所有 Months Day 对象 DayDate(最多 31,即 01 Sat 到 31 Mon)。

它没有显示 Day.DayDate!如何绑定?

您现在可以看到“Path=Day.DayDate”,但我已经尝试了几乎所有可能让我相信我从错误的角度接近这个的可能性。

非常感谢任何帮助

【问题讨论】:

    标签: wpf data-binding datatemplate collectionviewsource


    【解决方案1】:

    您的 Month 模板的 ListView 的 ItemsSource 需要绑定到 Days:

    改变

    ItemsSource="{Binding}"
    

    ItemsSource="{Binding Days}"
    

    其次,将每个模板视为处理该对象,因此更改此:

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

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

    它应该可以工作! ;)

    【讨论】:

    • 太棒了!做到了,非常感谢,所以 {Binding Days} 相当于 {Binding Path=Days} - 我希望绑定到的 Month 对象中的对象,我现在明白了。
    猜你喜欢
    • 2021-02-07
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多