Pergunta

I am displaying nodes in a TreeView control, and I am having issues with getting the data to display correctly with generics. More specifically, it seems that WPF is having trouble locating the data template. I'm guessing it is because the x:Type is declared to be NodeViewModel`1, and the actual type is NodeViewModel< INode>. However, the XAML will not compile if I try to use NodeViewModel< INode>.

I've got a HierachialDataTemplate that looks like the following:

<HierarchicalDataTemplate 
        ItemsSource="{Binding Path=Children}" 
        DataType="{x:Type viewModels:NodeViewModel`1}">
    <TextBlock Text="{Binding Path=Node.NodeDescription}" />                
</HierarchicalDataTemplate>

the NodeViewModel is declared as such:

public class NodeViewModel<T> where T : INode
{
    public T Node { get {...} set {...} }
}

the nodes interface looks as such:

public interface INode
{
    string NodeDescription { get; }
}
Foi útil?

Solução

I don't think that there what you're trying to do is supported. You could probably write a custom MarkupExtension to return a closed generic type, but it looks like you want to use the same DataTemplate for any NodeViewModel<T> where T : INode. In this case, WPF would need to support open generics as keys. Which it doesn't.

If that is the case, you're much better off just giving your HierarchicalDataTemplate a key, and applying it directly to the TreeView.

Or create a DataTemplateSelector and check the type of data item to select the proper template.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top