8
votes

I've figured out a way to bind user controls inside a tree view dynamically with ReactiveUI.

But ... The top level binding to the HierachicalDataSource is in the XAML not the code behind, and I need to set the ItemsSource directly and not use this.OneWayBind per the general pattern for ReactiveUI binding.

So, my question is: did I miss something in the ReactiveUI framework that would let me bind with this.OneWayBind and move the HierachicalDataTemplete into the code behind or a custom user control?

In particular- Is there another overload of OneWayBind supporting Hierarchical Data Templates, or a way to suppress the data template generation for the call when using it?

Update I've added selected item, and programatic support for Expand and Selected to my test project, but I had to add a style to the XAML. I'd like to replace that with a simple RxUI Bind as well. Updated the examples.

Here are the key details:

Tree Control in Main View

<TreeView Name="FamilyTree" >
                <TreeView.Resources>
                    <Style TargetType="{x:Type TreeViewItem}">
                        <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
                        <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
                  </Style>
                    <HierarchicalDataTemplate DataType="{x:Type local:TreeItem}" ItemsSource="{Binding Children}">
                        <reactiveUi:ViewModelViewHost ViewModel="{Binding ViewModel}"/>
                    </HierarchicalDataTemplate>
                </TreeView.Resources>
            </TreeView>

main view code behind

      public partial class MainWindow : Window, IViewFor<MainVM>
        {
            public MainWindow()
            {
                InitializeComponent();
                //build viewmodel
                ViewModel = new MainVM();
                //Register views
                Locator.CurrentMutable.Register(() => new PersonView(), typeof(IViewFor<Person>));
                Locator.CurrentMutable.Register(() => new PetView(), typeof(IViewFor<Pet>));
                //NB. ! Do not use 'this.OneWayBind ... ' for the top level binding to the tree view
                 //this.OneWayBind(ViewModel, vm => vm.Family, v => v.FamilyTree.ItemsSource);
                FamilyTree.ItemsSource = ViewModel.Family;
    }
...
}

MainViewModel

    public class MainVM : ReactiveObject
        {      
            public MainVM()
            {
                var bobbyJoe = new Person("Bobby Joe", new[] { new Pet("Fluffy") });
                var bob = new Person("Bob", new[] { bobbyJoe });
                var littleJoe = new Person("Little Joe");
                var joe = new Person("Joe", new[] { littleJoe });
                Family = new ReactiveList<TreeItem> { bob, joe };                                 
            _addPerson = ReactiveCommand.Create();
            _addPerson.Subscribe(_ =>
            {
                if (SelectedItem == null) return;
                var p = new Person(NewName);
                SelectedItem.AddChild(p);
                p.IsSelected = true;
                p.ExpandPath();
            });
    }
   public ReactiveList<TreeItem> Family { get; }
  ...
  }

TreeItem base class

public abstract class TreeItem : ReactiveObject
{
    private readonly Type _viewModelType;

    bool _isExpanded;
    public bool IsExpanded
    {
        get { return _isExpanded; }
        set { this.RaiseAndSetIfChanged(ref _isExpanded, value); }
    }

    bool _isSelected;
    public bool IsSelected
    {
        get { return _isSelected; }
        set { this.RaiseAndSetIfChanged(ref _isSelected, value); }
    }

    private TreeItem _parent;

    protected TreeItem(IEnumerable<TreeItem> children = null)
    {

        Children = new ReactiveList<TreeItem>();
        if (children == null) return;
        foreach (var child in children)
        {
            AddChild(child);
        }
    }

    public abstract object ViewModel { get; }
    public ReactiveList<TreeItem> Children { get; }

    public void AddChild(TreeItem child)
    {
        child._parent = this;
        Children.Add(child);
    }

    public void ExpandPath()
    {
        IsExpanded = true;
        _parent?.ExpandPath();
    }
    public void CollapsePath()
    {
        IsExpanded = false;
        _parent?.CollapsePath();
    }
}

Person Class

public class Person : TreeItem
    {
        public string Name { get; set; }
        public Person(string name, IEnumerable<TreeItem> children = null)
            : base(children)
        {
            Name = name;
        }
        public override object ViewModel => this;
    }

person view user control

<UserControl x:Class="TreeViewInheritedItem.PersonView"... >                 
    <StackPanel>
        <TextBlock Name="PersonName"/>
    </StackPanel>
</UserControl>

Person view code behind

public partial class PersonView : UserControl, IViewFor<Person>
    {
        public PersonView()
        {
            InitializeComponent();
            this.OneWayBind(ViewModel, vm => vm.Name, v => v.PersonName.Text);
        }
      ...
    }

Pet work the same as person.

And the full project is here ReactiveUI Tree view Sample

1

1 Answers

3
votes

I reviewed the ReactiveUI source and this is the only way to do this. The Bind helper methods always use a DataTemplate and not a HierarchicalDataTemplate.

So this approach will use the XAML binding for the very top level and then let you use ReactiveUI binding on all of the TreeView items.

I'll see about creating a pull request to handle this edge case.

Thanks, Chris