[英]WPF TabControl: a dictionary for tab headers
我有一个 TabControl 绑定到它的 viewmodel Items 属性:
<TabControl ItemsSource="{Binding Items}"/>
这是视图模型类:
public class ViewModel
{
public ObservableCollection<object> Items { get; } = new ObservableCollection<object>();
public ViewModel()
{
Items.Add(new Person() { FirstName = "Alan", LastName = "Turing" });
Items.Add(new Car() { ModelName = "Fiesta", Manifacturer = "Ford" });
}
}
Items
的类型是ObservableCollection<object>
; 这是因为每个选项卡代表不同类型的对象,在本例中为 Person 和 Car。
我想将选项卡的标题绑定到一个文本,该文本不能作为绑定类的属性使用,比如说手动提供的标题。
例如,我希望第一个选项卡将文本“Person”作为标题,第二个选项卡将文本“Car”作为标题:
我想到了:
在视图模型级别定义的Dictionary<object, string>
,我们称之为 Headers。
每次我向集合中添加一个对象时,我也会向 Headers 字典添加一个 Header。 它的关键是对象本身。
Person p = new Person() { FirstName = "Alan", LastName = "Turing" }; Headers.Add(p, "Person"); Items.Add(p);
但是绑定表达式怎么写呢?
<TabControl ItemsSource="{Binding Items}">
<TabControl.ItemTemplate>
<DataTemplate>
<Label Content="{Binding ????????}"/>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
即使可能,这个解决方案似乎也不是很“绑定友好”。
这里似乎有两个问题:动态地将信息附加到实例,并通过绑定访问它。
有任何想法吗?
代码,为了完整性。 我的课程:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Car
{
public string ModelName { get; set; }
public string Manifacturer { get; set; }
}
我的 DataTemplate,在<Winodow.Resources>
标签中定义。
<DataTemplate DataType="{x:Type local:Person}">
<StackPanel>
<Label Content="{Binding FirstName}"/>
<Label Content="{Binding LastName}"/>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Car}">
<StackPanel>
<Label Content="{Binding Manifacturer}"/>
<Label Content="{Binding ModelName}"/>
</StackPanel>
</DataTemplate>
您还可以覆盖分类模型的ToString()
方法并从那里返回您的友好名称。
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return "Person";
}
}
模板
<TabControl ItemsSource="{Binding Items}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.