绑定到TreeView

时间:2015-09-03 03:12:58

标签: c# wpf xaml binding treeview

我正在尝试将带有字典的类绑定到树视图。要绑定的对象的基类是ElementT:

// Base.cs in Base.dll

public class ElementT {

  protected ElementT mParent;
  private string mKey;
  protected Dictionary<string, ElementT> mMembers;
  //...
  public ElementT(string nodeKey) { mKey = nodeKey; }
  //...
  public ElementT Parent {
    get {return mParent}
    protected set { mParent = value; }
    }
  public string Key => mKey;
  public Dictionary<string, ElementT> Members => mMembers;
  //...
  }

public class NamespaceT : ElementT {

  public NamespaceT(string key) : base(key) {}
}

引用此基类是EngineT:

  // Engine.cs in Engine.dll (References base.dll)

  public sealed class EngineT {

  private NamespaceT mRoot;

  public EngineT() {

    mRoot = RootNamespaceT.GetInstance(null);
    //...
    }

  public ElementT RootElement => mRoot;
  }

internal class RootNamespaceT : NamespaceT {

  //...
  private RootNamespaceT() : base("Root") { }
  //...
  }

在引用Engine.dll的wpf窗口类中:

// MainWindow.xaml.cs (references Engine.dll) 

public partial class MainWindow : Window {

private EngineT mEngine;
private ObservableCollection<ElementT> mElementList;

public MainWindow() {

  mEngine = new EngineT();
  mElementList = new ObservableCollection<ElementT>();
  mElementList.Add(mEngine.RootElement);

  InitializeComponent();


  //ElementLibraryTreeView.ItemsSource = elementList; ????

  }
}

在XAML中:

   <TreeView ItemsSource="{Binding Source={StaticResource local:mElementList}}">
      <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type Key}" ItemsSource="{Binding Path=Members}">
          <TextBlock Text="{Binding Path=Key}"/>
        </HierarchicalDataTemplate>
      </TreeView.Resources>


    </TreeView>

我的目标是将密钥(mKey)与字典成员(mMembers)的成员列为n级别的子项。另外,我需要能够根据派生类类型(如Namespace)更改树形显示。 ElementT有许多不同的类型。我当前的问题是将ElementT的根实例绑定到代码中的树视图。我很感激能帮助我指出正确的方向。谢谢。

0 个答案:

没有答案