我在ViewModel中有一组Model对象。我想将TabControl绑定到这些对象,并使用DataTemplate从Model对象中提取信息。但是当我尝试这样做时,我收到以下错误信息:无法将类型为Model的对象强制转换为类型为TabItem的对象。经过一段时间的寻找解决方案,我发现了以下内容:
Silverlight TabControl已经损坏。使用ListBox和ContentControl的组合来模仿TabControl的行为。(这意味着我必须将ListBox装扮成TabControl)
TabControl没有覆盖PrepareContainerForItemOverride方法,解决方案是创建一个转换器。(不是很好,因为我需要在转换器中指定被转换对象的类型)
有人知道更好的解决方案吗?
XAML
<sdk:TabControl ItemsSource="{Binding Items, ElementName=MyControl}">
<sdk:TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</sdk:TabControl.ItemTemplate>
</sdk:TabControl>
C#
public ObservableCollection<Model> Items { get; set; }
public ViewModel()
Items = new ObservableCollection<Model>{
new Model { Name = "1"},
new Model { Name = "2"},
new Model { Name = "3"},
new Model { Name = "4"}
};
}
public class TabConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
List<TabSource> source = value as List<TabSource>;
if (source != null)
{
List<TabItem> result = new List<TabItem>();
foreach (TabSource tab in source)
{
result.Add(new TabItem()
{
Header = tab.Header,
Content = tab.Content
});
}
return result;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}