Self-Referencing Binding

2 posts, 0 answers
  1. Sergiy
    Sergiy avatar
    38 posts
    Member since:
    Jan 2012

    Posted 08 Nov 2012 Link to this post

    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')?
  2. Sergiy
    Sergiy avatar
    38 posts
    Member since:
    Jan 2012

    Posted 08 Nov 2012 Link to this post

    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>


  3. UI for WPF is Visual Studio 2017 Ready
Back to Top