[英]Nested databinding with WPF and C#
我正在尝试制定预算程序。 我需要在其中具有文本框列表的分组框的地方。
<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>
我需要以某种方式对具有组框的列表进行数据绑定(也许吗?),以便创建一个组框列表,其中的某些行将是带有货币值的文本。 这样我就可以创建一个名为“ Apartment”的组,其中有两行“ Rent $ 3000”和“ Maintenance $ 150”。 然后,我可以有一个名为“汽车”的第二组,例如带有“保险”,“贷款”和“维护”行。
但是我该如何绑定呢? 以及如何在C#中执行此操作。 我很茫然。
基于杰伊的评论,您可能想要创建一个层次数据模型。 注意我已经在属性上实现了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; }
}
然后,您的数据模板将如下所示:
<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>
我可能不在这里,但是听起来您想根据从异构对象列表绑定的对象类型来更改DataTemplate。
在这种情况下,您需要调查DataTemplateSelectors或为列表中要支持的每种类型创建DataTemplates。
例如,对于公寓,您可能具有:
<DataTemplate DataType="local:ApartmentBudget">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Text}" />
<TextBlock Text="{Binding Value}" />
</StackPanel>
</DataTemplate>
汽车可能看起来像:
<DataTemplate DataType="local:CarBudget">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Insurance}" />
<TextBlock Text="{Binding Loan}" />
<TextBlock Text="{Binding Maintenance}" />
</StackPanel>
</DataTemplate>
然后,您的ItemsControl可以设置为:
<ItemsControl ItemSource="{Binding BudgetItems}">
将根据数据类型选择正确的DataTemplate。 通过创建自定义DataTemplateSelector,您甚至可以拥有更多控制权。
有关更多信息,请参见https://msdn.microsoft.com/zh-cn/library/ms742521(v=vs.100).aspx 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.