如何使用递归构建自定义控件?

时间:2018-03-30 14:50:18

标签: c# wpf recursion mvvm

我正在尝试构建一个相当复杂的自定义控件。

我想在View Model中使用递归来构建控件。我会尽量保持清醒。

我有两个类,Publisher和Developer

Publisher类如下所示:

render() {
  const Layout = createRootNavigator(this.state.load);
  <Layout />
}

我的开发人员类看起来像这样:

public class Publisher
{
  public Publisher()
  {
    SubPublishers.CollectionChanged += SubPublishers_CollectionChanged;
    ChildDevelopers.CollectionChanged += SubPublishers_CollectionChanged;
  }

  private ObservableCollection<Publisher> subPublishers;
  public ObservableCollection<Publisher> SubPublishers
  {
    get
    {
       if (subPublishers == null)
           subPublishers = new ObservableCollection<Publisher>();
       return subPublishers;
    }
  }

  private ObservableCollection<Developer> childDevelopers;
  public ObservableCollection<Developer> ChildDevelopers
  {
    get
    {
       if (childDevelopers == null)
           childDevelopers = new ObservableCollection<Developer>();
       return childDevelopers;
    }
  }

所以是的,Publisher是n层。它可以有一个开发人员集合,每个开发人员都可以拥有自己的开发人员集合。

转到我的主视图模型:

public class Developer : NotifyPropertyChanged
{
   public Developer(string Title)
   {
     this.Title = Title;
   }

   private string title;
   public string Title
   {
     get
     {
       return this.title;
     }
     set
     {
       this.title = value;
       OnPropertyChanged("Title");
     }
   }

因此,您可以在此处查看可能的方案。现在,我试图弄清楚如何建立一个控制这个数据。

我想实际绑定到ParentPublisher,因为添加的所有内容(SubPublishers和Child Developers)最终都将成为Parent的扩展。

我会使用ObservableCollection并将ItemSource用于此ParentPublisher吗?

任何提示或建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

一种方法是使UserControl超出第一层作为DataTemplate。然后根据需要在DataTemplate中显示数据。在DataTemplate内,再次使用内部数据引用UserControl

示例:显然修改了布局以使您受益,但为了简单起见,我这样做了。

<UserControl x:Class="WPF_Question_Answer_App.PublisherView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:WPF_Question_Answer_App"
             mc:Ignorable="d"
             d:DesignHeight="450"
             d:DesignWidth="800">

    <UserControl.Resources>
        <DataTemplate x:Key="DeveloperTemplate">
            <TextBlock Text="{Binding Title}" /> <!--show the developer data-->
        </DataTemplate>

        <DataTemplate x:Key="PublisherTemplate">
            <local:PublisherView /> <!-- reference ourself for recursion-->
        </DataTemplate>
    </UserControl.Resources>

    <StackPanel>
        <ItemsControl ItemsSource="{Binding ChildDevelopers}"
                      ItemTemplate="{StaticResource DeveloperTemplate}" />
        <ItemsControl ItemsSource="{Binding SubPublishers}"
                      ItemTemplate="{StaticResource PublisherTemplate}" />
    </StackPanel>
</UserControl>