使用WPF和C#嵌套数据绑定

1 c# data-binding wpf xaml nested

我正在尝试制定预算计划.我需要在哪里放置带有文本块列表的分组框.

<ItemsControl DataContext="{Binding}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <GroupBox Header="{Binding}">
        <ItemsControl DataContext="{Binding}">
          <ItemsControl.ItemTemplate>
            <DataTemplate>
              <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Text}" />
                <TextBlock Text="{Binding Value}" />
              </StackPanel>
            </DataTemplate>
          </ItemsControl.ItemTemplate>
        </ItemsControl>
      </GroupBox>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)

我需要以某种方式将一个列表(可能是?)与groupboxs数据绑定,所以我创建了一个组合框列表,其中一些行是一个带有货币值的文本.这样我就可以创建一个名为"Apartment"的组,其中包含两行"Rent $ 3000"和"Maintenance $ 150".然后我可以有一个名为"Car"的第二组,例如"保险","贷款"和"维护".

但是我该如何对此进行数据处理呢?我将如何在C#中执行此操作.我不知所措.

cor*_*erm 5

根据Jay的评论,你可能想要创建一个Hierarchical数据模型.注意我已经在属性上实现了INotifyPropertyChanged

public class BudgetLineItem : INotifyPropertyChanged
{
   public string Name { get; set; }
   public decimal Cost { get; set; }
}

public class BudgetGroup : INotifyPropertyChanged
{
   public string GroupName { get; set; }
   public ObservableCollection<BudgetLineItem> LineItems { get; set; }
}

public class BudgetViewModel : INotifyPropertyChanged
{
   public ObservableCollection<BudgetGroup> BudgetGroups { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后您的数据模板将如下所示:

<ItemsControl DataContext="{Binding ViewModel}"
              ItemsSource="{Binding BudgetGroups}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <GroupBox Header="{Binding GroupName}">
        <ItemsControl ItemsSource="{Binding LineItems}">
          <ItemsControl.ItemTemplate>
            <DataTemplate>
              <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Name}" />
                <TextBlock Text="{Binding Cost}" />
              </StackPanel>
            </DataTemplate>
          </ItemsControl.ItemTemplate>
        </ItemsControl>
      </GroupBox>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)