【问题标题】:How to Use a TreeView as a Binding Source for Other Controls如何使用 TreeView 作为其他控件的绑定源
【发布时间】:2018-02-23 02:07:42
【问题描述】:

考虑一个任务类:

TaskID
ParentID
Title
<several other properties>
Description
SubTasks <-- a collection of tasks

首先我填充一个名为 AllTask​​s 的任务层次结构,然后通过以下方式将其加载到 TreeView 中:

TaskTree.DataContext = AllTasks

效果很好。现在,当用户单击 TreeView 中的任务时,我想用任务数据填充其他几个控件。我将只考虑 Description 属性,因为它足以说明问题。

我的 TreeView 定义如下:

<TreeView
    x:Name="TaskTree"
    SelectedValuePath="Task">
    <TreeView ItemsSource="{Binding}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Path=SubTasks}">
                <TextBlock Text="{Binding Path=Title}" />
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</TreeView>

应该显示用户选择的任务的描述属性的文本框由以下定义:

<DockPanel
    DataContext="{Binding ElementName=TaskTree}">
    <TextBox
        x:Name="txtDescription" 
        Text="{Binding Path=SelectedItem.Discussion}"
</DockPanel>

TextBox 中没有显示任何内容。我试过设置....

Text="{Binding Path=Discussion}"

...但这也不起作用。我尝试了其他组合,但无济于事。什么有效?

【问题讨论】:

  • 你应该为此实现一个视图模型。请参阅 MVVM。

标签: wpf binding treeview


【解决方案1】:

您没有在名为“TaskTree”的外部TreeView 中选择任何Task。去掉外面的:

<TreeView ItemsSource="{Binding}" x:Name="TaskTree">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Task}" ItemsSource="{Binding Path=SubTasks}">
            <TextBlock Text="{Binding Path=Title}" />
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

...然后尝试绑定到 its SelectedItem 属性:

<TextBox x:Name="txtDescription" Text="{Binding Path=SelectedItem.Discussion, ElementName=TaskTree}" />

【讨论】:

  • 你知道,我盯着那个 XAML 看了好几个小时,从来没有注意到我在另一个树视图中有一个树视图。当然这是不正确的。我的脸有多红。所以我所要做的就是删除第二个“
  • 我注意到我刚刚在我的代码中删除了我想告诉你他他
  • @SezMe:请记得投票给有用的答案:stackoverflow.com/help/someone-answers
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
相关资源
最近更新 更多