gpt4 book ai didi

silverlight - 在 Silverlight 中对多种对象类型进行分层模板化

转载 作者:行者123 更新时间:2023-12-04 06:56:25 24 4
gpt4 key购买 nike

在 Silverlight (4) TreeView 控件中实现以下层次结构的最佳方法是什么? (其中 Item 和 Group 是可以存在于树中的类)。


Group
|
|-Item
|
|-Group
| |
| |-Item
| |
| |-Item
|
|-Item

如果需要,结构当然可以任意地比这更复杂。

HierarchicalDataTemplates 似乎是解决这个问题的方法,但我特别无法理解如何应用模板来正确解释不同的类。

对 WPF 提出了一个类似的问题,该问题的答案使用了 HierarchicalDataTemplate 上的 TargetType 属性,但我不确定该属性是否在 Silverlight 版本中可用,因为我似乎无法在我的环境中访问它。

最佳答案

对于 Silverlight,您可能需要创建一个转换器来帮助执行此操作。例如,“目标类型数据模板选择器”或类似的。

虽然您可以更高级,但这里是 Silverlight 单元测试框架的一个示例,它允许您为硬编码类型提供数据模板的实例。大概 20 分钟就可以制作一个通用版本。

要使用它,您需要提供数据模板的实例 - 但在您的情况下,您可能需要使它们分层。

<local:DataTemplateSelector 
x:Key="DetailsViewDataTemplate"
DefaultDataTemplate="{StaticResource DefaultDataTemplate}"
TestMethodTemplate="{StaticResource TestMethodDataTemplate}"
TestClassTemplate="{StaticResource TestClassDataTemplate}"/>

这是实现:
/// <summary>
/// A specialized data template selector.
/// </summary>
public sealed class DataTemplateSelector : IValueConverter
{
/// <summary>
/// Gets or sets the default data template.
/// </summary>
public DataTemplate DefaultDataTemplate { get; set; }

/// <summary>
/// Gets or sets the test method template.
/// </summary>
public DataTemplate TestMethodTemplate { get; set; }

/// <summary>
/// Gets or sets the test class template.
/// </summary>
public DataTemplate TestClassTemplate { get; set; }

/// <summary>
/// Initializes a new instance of the DataTemplateSelector type.
/// </summary>
public DataTemplateSelector()
{
}

/// <summary>
/// Convert a value to a data template.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="targetType">The target parameter.</param>
/// <param name="parameter">ConverterParameter value.</param>
/// <param name="culture">The culture parameter.</param>
/// <returns>Returns the object.</returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
Type type = value.GetType();

if (typeof(TestMethodData).TypeHandle == type.TypeHandle)
{
return TestMethodTemplate;
}
else if (typeof(TestClassData).TypeHandle == type.TypeHandle)
{
return TestClassTemplate;
}
}

return DefaultDataTemplate;
}

/// <summary>
/// No 2-way databinding support.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="targetType">The target parameter.</param>
/// <param name="parameter">ConverterParameter value.</param>
/// <param name="culture">The culture parameter.</param>
/// <returns>Returns the object.</returns>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}

关于silverlight - 在 Silverlight 中对多种对象类型进行分层模板化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2493551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com