在 Silverlight 2 中渲染异构视图模型集合
-
13-09-2019 - |
题
我有一个表示格式化内容的视图模型层次结构:
public abstract class ContentPartViewModel : ViewModel
{
}
public class TextContentPartViewModel : ContentPartViewModel
{
public string Text { ... }
}
public class TitleContentPartViewModel : TextContentPartViewModel
{
}
public class HyperlinkContentPartViewModel : TextContentPartViewModel
{
public string Uri { ... }
}
我有一个包含视图模型,其中包含以下内容的集合 ContentPartViewModel
要渲染的s:
public class ContentViewModel
{
public ICollection<ContentPartViewModel> ContentParts { ... }
}
然后我有一个 ContentView
呈现内容的所有部分:
<UserControl ...>
<ItemsControl ItemsSource="{Binding ContentParts}"/>
</UserControl>
在理想的世界中,我只会定义一个 DataTemplate
对于每个内容部分类型,它们都会相应地呈现。但是,Silverlight 不支持 DataType
财产在 DataTemplate
类,所以这不是一个选择。
另一种选择是提供 DataTemplateSelector
并将视图模型类型映射到 DataTemplate
我。唉, ItemsControl
在 SL2 中没有 ItemTemplateSelector
财产 - 只有一个 ItemTemplate
财产。
这让我别无选择,只能提供一个 ItemTemplate
然后使用转换器关闭除与该内容部分相关的部分之外的所有 UI:
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Text}" FontWeight="Bold" Visibility="{Binding Converter={StaticResource TitleContentPartConverter}}"/>
<TextBlock Text="{Binding Text}" Visibility="{Binding Converter={StaticResource TextContentPartConverter}}"/>
<HyperlinkButton Content="{Binding Text}" NavigateUri="{Binding Uri}" Visibility="{Binding Converter={StaticResource HyperlinkContentPartConverter}}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
对于性能和代码的可读性/正确性来说,这显然是相当糟糕的。这也使我更难正确格式化输出。那么,问题:
- 谁能推荐一个更好的方法来在 SL2 中做到这一点?
- 谁能确认SL3的情况是否有所改善?
谢谢,肯特
解决方案
是的。Silverlight 2 或 Silverlight 3 不支持 DataTemplate 中的 DataType。
您可以在 Silverlight 中解决 ItemTemplateSelector。请看一下这个示例。
http://silverlight.net/forums/t/12598.aspx
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
DataTemplateSelector selector = this.ItemTemplateSelector;
if (null != selector)
{
((ContentPresenter)element).ContentTemplate = selector.SelectTemplate(item, element);
}
}
不隶属于 StackOverflow