【问题标题】:How bind an object to treeview from Xaml如何从 Xaml 将对象绑定到树视图
【发布时间】:2012-11-13 21:52:26
【问题描述】:

我正在尝试通过 XAML 将对象绑定到 treeviewcontrol WPF,但我将 treview 设为空。当我通过treeview.items.add(GetNode()) 这样做时,它就可以工作了。

我正在使用 MVVM Framework(caliburn.Micro) 我想在 Xaml 中执行此操作,如何在 xaml 中分配项目源属性?我尝试创建 Node 类的属性并在属性中调用方法 GetNode(),并将该属性分配为树视图的 itemssource 并将 List 更改为 Observable 集合。问题还是一样。

在执行 treeview.items.Add(GetNode()) 时工作 Xaml,它返回一个节点,并且 i 将节点集合分配给 Hireachial 模板。

<TreeView  Name="treeview2" 
            Grid.RowSpan="2"
            Grid.ColumnSpan="2"
            ItemContainerStyle="{StaticResource StretchTreeViewItemStyle}" Width="300">
            <TreeView.ItemTemplate>
                 <HierarchicalDataTemplate  ItemsSource="{Binding Nodes}">
                      <DockPanel LastChildFill="True">
                          <TextBlock  Padding="15,0,30,0" Text="{Binding Path=numitems}" TextAlignment="Right" 
    DockPanel.Dock="Right"/>
                          <TextBlock  Text="{Binding Path=Text}" DockPanel.Dock="Left" TextAlignment="Left" />
                      </DockPanel>
                 </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
  </TreeView>

服务器端代码:

this.treeview2.Items.Add(GetNode());

GetNode 递归地构建一个 Node 类型的列表。

public class Node
{
    public string Text { get; set; }
    public List<Node> Nodes { get; set; }
    public ObservableCollection<Node> Nodes{get;set;} // with list and observable collection same results
    public int numitems { get; set; }
}

【问题讨论】:

    标签: c# wpf xaml treeview caliburn.micro


    【解决方案1】:

    除了看起来很好的HierarchicalDataTemplate之外,添加一个绑定到TreeView的ItemsSource属性:

    public class ViewModel
    {
       private List<Node> _rootNodes;
       public List<Node> RootNodes 
       {
         get
         {
           return _rootNodes;
         }
         set
         {
           _rootNodes = value;
           NotifyPropertyChange(() => RootNodes);
         }
       }
    
       public ViewModel()
       {
          RootNodes = new List<Node>{new Node(){Text = "This is a Root Node}", 
                                     new Node(){Text = "This is the Second Root Node"}};
       }
    

    在 XAML 中:

    <TreeView ItemsSource="{Binding RootNodes}"
              .... />
    

    编辑:删除不需要 this.Treeview.... 的调用。尽量减少引用 UI 元素的代码量。您可以使用绑定完成所有操作,无需在代码中操作 UI 元素。

    【讨论】:

      猜你喜欢
      • 2012-06-21
      • 1970-01-01
      • 2022-01-08
      • 2011-05-26
      • 1970-01-01
      • 2020-03-06
      • 2021-12-19
      • 1970-01-01
      • 2013-06-08
      相关资源
      最近更新 更多