我认为您应该考虑避免使用 Telerik 的课程(在我看来,在这种情况下,这会使事情变得有些复杂)。
标准DataTemplateSelector
实现呢?自己实现非常容易!
首先,您声明抽象类的“经典”实现DataTemplateSelector
:
public abstract class DataTemplateSelector : ContentControl
{
public virtual DataTemplate SelectTemplate(object item, DependencyObject container)
{
return null;
}
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
ContentTemplate = SelectTemplate(newContent, this);
}
}
然后你可以写你自定义DataTemplateSelector
...
public class myTemplateSelector : DataTemplateSelector
{
public DataTemplate Template1 { get; set; }
public DataTemplate Template2 { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
// No template...
if (item == null)
return null;
// Enumeration discriminant:
if (item is BoundTemplateDiscriminantType)
switch ((BoundTemplateDiscriminantType)item)
{
case BoundTemplateDiscriminantType.Type1:
return Template1;
case BoundTemplateDiscriminantType.Type2:
return Template2;
// Not implemented...
default:
throw new NotImplementedException();
}
// Integer discriminant:
else if (item is int)
{
return (int)item > 0 ? Template1 : Template2;
}
// Other discriminants...
else
// Not yet implemented...
throw new NotImplementedException();
}
}
...最后是 XAML 设计(不是通常的ListBoxItem,但在这种情况下是可滚动的内容):
<ScrollViewer>
<ScrollViewer.ContentTemplate>
<DataTemplate>
<utilities:myTemplateSelector Content="{Binding Path=BoundDiscriminant, Mode=OneWay}">
<!--Content of first template...-->
<utils:myTemplateSelector.Template1>
<DataTemplate>
<TextBlock Text={Binding Path=BoundDescription, Mode=OneWay} />
</DataTemplate>
</utils:myTemplateSelector.Template1>
<!--Content of second template...-->
<utils:myTemplateSelector.Template2>
<DataTemplate>
</DataTemplate>
</utils:myTemplateSelector.Template2>
... and so on...
</utilities:myTemplateSelector>
</DataTemplate>
</ScrollViewer.ContentTemplate>
</ScrollViewer>