请考虑以下代码:
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绑定到这个词典(myPersonInfo) 对于每个人创建一个选项卡,其中选项卡标题将是该人的名称,然后该选项卡的内容将显示HealtInfo。
我在XAML
中绑定了这个词典我有以下内容:
<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?
答案 0 :(得分:2)
创建“聚合”类并在ObservableCollection
中使用它,数据绑定很好地支持
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);
答案 1 :(得分:2)
您需要更改xaml中的绑定。
<TabControl ItemsSource="{Binding myPersonInfo}" SelectedIndex="0">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Key.Name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value.BMI}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
此外,myPersonInfo应该是一个属性。所以声明如下:
public Dictionary<Person, HealthInfo> myPersonInfo { get; set; }
虽然此代码可以使用,但请考虑重构模型以使其更清晰。