gpt4 book ai didi

c# - 使用 WPF 和 C# 进行嵌套数据绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 20:33:05 25 4
gpt4 key购买 nike

我正在尝试制定预算计划。我需要在其中包含文本 block 列表的组框。

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

我需要以某种方式将列表(也许?)与组框进行数据绑定(bind),因此我将创建一个组框列表,其中一些行是带有货币值的文本。这样我就可以创建一个名为“Apartment”的组,其中包含两行“Rent $3000”和“Maintenance $150”。然后我可以创建第二个名为“汽车”的组,其中包含“保险”、“贷款”和“维护”等行。

但是我该如何对它进行数据绑定(bind)呢?我将如何在 C# 中执行此操作。我很茫然。

最佳答案

根据 Jay 的评论,您可能想要创建一个分层数据模型。请注意,我已将对属性的 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>

关于c# - 使用 WPF 和 C# 进行嵌套数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6445423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com