[英]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.