0

Мне нужно использовать ObservableCollection и только один класс. Вот мой код. По какой-то причине я не могу заставить TreeView заполнить коллекцию Observable. Любая помощь будет оценена по достоинству.Использование HierarchicalDataTemplate и наблюдаемого в WPF

XAML:

<UserControl x:Class="ValidationWPF.ValidationUserControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" 
      xmlns:local="clr-namespace:ValidationWPF.DataSources" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"> 
    <UserControl.Resources> 
     <local:ValidationItem x:Key="ValidationMessages" /> 

     <DataTemplate x:Key="Messages"> 
      <TextBlock Text="{Binding Messages}" /> 
     </DataTemplate> 

     <HierarchicalDataTemplate x:Key="SubItem" ItemTemplate="{StaticResource Messages}" ItemsSource="{Binding Messages}" > 
      <TextBlock Text="{Binding subItem}" /> 
     </HierarchicalDataTemplate> 

     <HierarchicalDataTemplate ItemTemplate="{StaticResource SubItem}" x:Key="ItemTemplate" 
       ItemsSource="{Binding subItem}"> 
      <TextBlock Text="{Binding item}" FontWeight="Bold" /> 
     </HierarchicalDataTemplate> 

    </UserControl.Resources> 

    <Grid> 
     <telerik:RadTreeView ItemsSource="{Binding Source={StaticResource ValidationMessages}}" 
       ItemTemplate="{StaticResource ItemTemplate}" x:Name="RadTreeView"/> 
    </Grid> 
</UserControl> 

КЛАСС:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Collections.ObjectModel; 

namespace ValidationWPF.DataSources 
{ 
    class ValidationItem : ObservableCollection<ValidationItem> 
    { 
     public ValidationItem() 
     { 
     } 

     public ValidationItem(Item item, SubItem subItem, string Messages) 
     { 
      this.item = item; 
      this.subItem = subItem; 
      this.Message = Messages; 
     } 

     public string Message { get; set; } 

     public SubItem subItem { get; set; } 

     public Item item { get; set; } 

     public ObservableCollection<ValidationItem> ValidationItems 
     { 
      get 
      { 
       Add(new ValidationItem(Item.Customer, SubItem.Name, "Customer Name Cannot be Null")); 
       Add(new ValidationItem(Item.Customer, SubItem.Phone, "Phone number cannot be Null")); 
       Add(new ValidationItem(Item.Customer, SubItem.Phone, "Phone number must be in the format (###)###-####")); 
       Add(new ValidationItem(Item.Customer, SubItem.Address, "Customer Address cannot be Null")); 
       return ValidationItems; 
      } 
     } 
    } 

    public enum Item 
    { 
     Customer 
    } 

    public enum SubItem 
    { 
     Address, 
     Phone, 
     Name 
    } 
} 
+0

Is ValidationItem действительно частный? – Phil

ответ

1

UPDATE: Хорошо, много здесь происходит, так что потребовалось некоторое время, чтобы действительно понять. Две вещи.

Изменить конструктор по умолчанию вас модель для

public ValidationItem() 
    { 
     Add(new ValidationItem(Item.Customer, SubItem.Name, "Customer Name Cannot be Null")); 
     Add(new ValidationItem(Item.Customer, SubItem.Phone, "Phone number cannot be Null")); 
     Add(new ValidationItem(Item.Customer, SubItem.Phone, "Phone number must be in the format (###)###-####")); 
     Add(new ValidationItem(Item.Customer, SubItem.Address, "Customer Address cannot be Null")); 
    } 

Другой изменить свойство «подпозиция». HierarchicalDataTemplate ожидает, что ItemSource будет IEnumerable. Поэтому измените свойство на

public IEnumerable<SubItem> subItems 

Даже если у вас его есть, сделайте его IEnumerable. Вам также нужно изменить HierarchicalDataTemplates к

<HierarchicalDataTemplate x:Key="SubItem"> 
     <TextBlock Text="{Binding}" /> 
    </HierarchicalDataTemplate> 

    <HierarchicalDataTemplate ItemTemplate="{StaticResource SubItem}" x:Key="ItemTemplate" 
      ItemsSource="{Binding subItems}"> 
     <TextBlock Text="{Binding item}" FontWeight="Bold" /> 
    </HierarchicalDataTemplate> 

Это также помогает отлаживать приложения и просматривать в окне вывода. Если есть какие-либо проблемы с привязкой, это скажет вам. Что-то вроде «Ошибка привязки, не удалось найти свойство« Сообщения ».

+0

Нет. Он действует так, как будто в коллекции Observable нет ничего ... Он компилируется и работает нормально, без ошибок. Я думаю, что может возникнуть проблема, когда я добавляю вещи в свою наблюдаемую коллекцию. – JLott

+0

Сделал большое изменение для моего сообщения, когда я действительно понял, что вы делаете. –

+0

Спасибо за помощь. Я в конечном итоге занял совершенно новое направление и добавил списки в наблюдаемые коллекции. – JLott

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