gpt4 book ai didi

c# - 将 XAML 绑定(bind)到字典

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:18 27 4
gpt4 key购买 nike

考虑以下代码:

public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}

public class HealthInfo {
public int BMI { get; set; }
public int HeartRate { get; set; }
public string DietPlan { get; set; }
}


Dictionary<Person, HealthInfo> myPersonInfo = new Dictionary<Person, HealthInfo>();

myPersonInfo.Add( new Person { Id = 1, Name = "Name1", Surname = "Surname1" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name2", Surname = "Surname2" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name3", Surname = "Surname3" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name4", Surname = "Surname4" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );

我正在尝试从我的 xaml 绑定(bind)到这个 Dictionary(myPersonInfo)为每个人创建一个选项卡,其中选项卡标题将是该人的姓名,然后该选项卡的内容将显示 HealtInfo。

我在我的 XAML 中绑定(bind)到这个字典有困难

我有以下内容:

<TabControl ItemsSource="{Binding myPersonInfo.Keys}" SelectedIndex="0">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Key.Value.BMI}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>

如何使用 ItemTemplate 的 Key(Person) 属性和如何将 Value(HealtInfo) 的属性用于当前 Key 的 ContentTemplate?

最佳答案

创建“聚合”类并在 ObservableCollection 中使用它,数据绑定(bind)很好地支持了它

 public class PersonHealthInfo
{
public Person Person {get; set; }
public HealthInfo HealthInfo {get; set; }
}

ObservableCollection<PersonHealthInfo> persons = new ObservableCollection<PersonHealthInfo>();

var person1 = new PersonHealthInfo
{
Person = new Person { Id = 1, Name = "Name1", Surname = "Surname1" },
HealthInfo = new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 }
}

persons.Add(person1);

关于c# - 将 XAML 绑定(bind)到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43179448/

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