WPF TreeView template with different classes

后端 未结 2 1949
迷失自我
迷失自我 2021-01-28 11:13

How to write XAML for WPF TreeView so when I bind ViewModel with following structure?

public class A
{
    int Id { get; set; }
    string Name { get; set; }
             


        
2条回答
  •  一整个雨季
    2021-01-28 11:45

    You could combine the ItemsB and ItemsC collections of class A into a CompositeCollection.

    Since HierarchicalDataTemplate.ItemsSource is not a collection, but a BindingBase it seems not possible to do this directly in XAML. You may however write a Binding Converter:

    public class ClassAItemsConverter : IValueConverter
    {
        public object Convert(
            object value, Type targetType, object parameter, CultureInfo culture)
        {
            var a = (A)value;
    
            return new CompositeCollection
            {
                new CollectionContainer() { Collection = a.ItemsB },
                new CollectionContainer() { Collection = a.ItemsC }
            };
        }
    
        public object ConvertBack(
            object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
    

    The templates would look like this:

    
        
    
        
            
        
    
        
            
        
    
        
            
        
    
        
            
        
    
    

提交回复
热议问题