2016-08-25 4 views
2

Я работаю над добавлением некоторых свойств в класс расширения TreeView. Мне нужны дополнительные поля для контекста при щелчке по одному из элементов в дереве. Кажется, я не вижу древовидного представления, чтобы показывать какие-либо данные, которые я им даю. В моих MainView.cs я просто указать источник элементов, как, например:Расширение TreeView с дополнительными свойствами?

TreeMenu.ItemsSource = (an ObservableCollection of ParentItems)

XAML:

<Grid x:Name="TreeGrid" Width="350" HorizontalAlignment="Left"> 
     <TreeView Name="TreeMenu" Background="Red" Foreground="Black"> 
      <TreeView.ItemTemplate> 
       <HierarchicalDataTemplate DataType="{x:Type model:ParentItem}" ItemsSource="{Binding ChildItems}"> 
        <TextBlock Text="{Binding Text}" /> 
       </HierarchicalDataTemplate> 
      </TreeView.ItemTemplate> 
     </TreeView> 
    </Grid> 

модель объекта:

public class ParentItem : TreeViewItem, INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    protected void NotifyPropertyChanged(string info) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info)); 
    } 

    public ParentItem() 
    { 
     _text = ""; 
     _url = ""; 
     _childItems = new ObservableCollection<ChildItem>(); 
    } 

    private string _text; 
    public string Text 
    { 
     get 
     { 
      return _text; 
     } 
     set 
     { 
      _text = value; 
      NotifyPropertyChanged("Text"); 
     } 
    } 

    private string _url; 
    public string URL 
    { 
     get 
     { 
      return _url; 
     } 
     set 
     { 
      _url = value; 
      NotifyPropertyChanged("URL"); 
     } 
    } 

    private ObservableCollection<ChildItem> _childItems; 
    public ObservableCollection<ChildItem> ChildItems 
    { 
     get 
     { 
      return _childItems; 
     } 
     set 
     { 
      _childItems = value; 
      NotifyPropertyChanged("ChildItems"); 
     } 
    } 
} 

Обратите внимание, что ChildItem почти идентичный ParentItem, минус объект коллекции. Первоначально я пробовал расширение TreeNode в классах объектов, но у этой проблемы была такая же проблема.

Кто-нибудь знает, почему мой TreeView не появится? Я что-то упускаю, расширяя TreeView?

ответ

2

Отсутствие уточнений TreeViewItem.

Мы не видим, как вы назначаете свою коллекцию, чтобы они могли что-то сделать неправильно.

Это делает работу:

Код

using System.Collections.ObjectModel; 
using System.Windows; 

namespace WpfApplication4 
{ 
    /// <summary> 
    ///  Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      DataContext = new ItemCollection 
      { 
       new Item 
       { 
        Text = "A", 
        Items = new ItemCollection 
        { 
         new Item 
         { 
          Text = "B", 
          Items = new ItemCollection 
          { 
           new Item 
           { 
            Text = "C" 
           } 
          } 
         } 
        } 
       } 
      }; 
     } 
    } 

    public class Item 
    { 
     public string Text { get; set; } 

     public ItemCollection Items { get; set; } 
    } 

    public class ItemCollection : ObservableCollection<Item> 
    { 
    } 
} 

XAML

<Window x:Class="WpfApplication4.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:WpfApplication4" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="350" Width="525"> 

    <Grid> 
     <TreeView ItemsSource="{Binding}"> 
      <TreeView.ItemTemplate> 
        <HierarchicalDataTemplate DataType="local:Item" ItemsSource="{Binding Items}"> 
       <TextBlock Text="{Binding Text}" /> 
       </HierarchicalDataTemplate> 
      </TreeView.ItemTemplate> 
     </TreeView> 
    </Grid> 
</Window> 

Результат

enter image description here

+0

Отлично, все, что я закончил, не расширяет TreeViewItem в моих классах. Это, похоже, было проблемой. Спасибо! –

+0

Вы приветствуете !!! – Aybe

Смежные вопросы