This is a migrated thread and some comments may be shown as answers.

Self-Referencing Binding

1 Answer 95 Views
TreeView
This is a migrated thread and some comments may be shown as answers.
Sergiy
Top achievements
Rank 1
Sergiy asked on 08 Nov 2012, 02:41 PM
Hi, 

I have got model:

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentCategoryId { get; set; }
    public virtual Category ParentCategory { get; set; }
    public virtual ICollection<Category> SubCategories { get; set; }
}

And in MVVM:

private ObservableCollection<Category> _categories;
public ObservableCollection<Category> Categories
{
    get { return _categories; }
    set
    {
        if (_categories == value) return;
 
        _categories = value;
        OnPropertyChanged("Categories");
    }
}

I found an example, but I don't want to create a new model, and even more so to edit an existing one.
Could you explain to me step-by-step, how I can bind the data to treeview (with parents and their childs')?

1 Answer, 1 is accepted

Sort by
0
Sergiy
Top achievements
Rank 1
answered on 08 Nov 2012, 04:05 PM
thanks, I understand and wrote the following code

      
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
          var category = value as Category;
          if (null != category)
          {
                  if (category.SubCategories.Count > 0)
                  {
                      return category.SubCategories.Where(i => i.ParentCategoryId == category.Id);
                  }
          }
   
          var categories = value as ObservableCollection<Category>;
          if (categories != null && categories.Count > 0)
          {
              return new ObservableCollection<Category>(categories.Where(c => c.ParentCategory == null));
          }
 
 
          return null;
      }

and xaml

<t:RadTreeView       SelectedValuePath="Name"
               ItemsSource="{Binding Categories, Converter={StaticResource treeHierarchyConverter}}">
     
    <t:RadTreeView.ItemTemplate>
        <HierarchicalDataTemplate
            ItemsSource="{Binding Converter={StaticResource treeHierarchyConverter}}">
            <TextBlock Text="{Binding Name}" />
        </HierarchicalDataTemplate>
    </t:RadTreeView.ItemTemplate>
</t:RadTreeView>


Tags
TreeView
Asked by
Sergiy
Top achievements
Rank 1
Answers by
Sergiy
Top achievements
Rank 1
Share this question
or