首页 > 解决方案 > WPF HierarchicalDataTemplate:从 ItemTemplate 绑定回父级

问题描述

给定以下模板,我将其与 Telerik RadPanelBar 控件一起使用,以便提供一个类似于手风琴的视图,其中每个栏项目显示一个标题,许多控件用于收集标准,然后是“清除”和“搜索”按钮......

        <HierarchicalDataTemplate x:Key="radPanelBarSearchCriteriaItemTemplate"
                                  ItemsSource="{Binding Criteria, Converter={StaticResource radPanelBarItemContentSingleItemConverter}}">
            <TextBlock Margin="5 4 5 6"
                       Text="{Binding Path=Header}" />
            <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <ContentPresenter Content="{Binding}" />
                        <StackPanel HorizontalAlignment="Right"
                                    Margin="0 20 0 0"
                                    Orientation="Horizontal">
                            <telerik:RadButton Command="{Binding Path=DataContext.ClearCommand, RelativeSource={RelativeSource TemplatedParent}}"
                                               Style="{StaticResource dialogClearButtonStyle}" />
                            <telerik:RadButton Command="{Binding Path=DataContext.SearchCommand, RelativeSource={RelativeSource AncestorType={x:Type telerik:RadPanelBar}}}"
                                               Style="{StaticResource dialogSearchButtonStyle}" />
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>

我遇到的问题是按钮绑定在错误的级别;“ClearCommand”和“SearchCommand”都是与模板中TextBlock引用的“Header”相同的对象上的属性,而不是“Criteria”的属性(这也是同一对象的属性)。

仅供参考:在 HierarchicalDataTemplate 的 ItemsSource 上使用的转换器只需要一个对象并将其作为对象列表呈现给模板。

有人可以帮我找到正确的方法来定义按钮上的命令绑定,以便返回到父对象并正确引用“ClearCommand”和“SearchCommand”。正如您在上面看到的,我一直在尝试各种组合,但似乎没有找到合适的组合。

谢谢。

标签: .netwpfdata-bindinghierarchical

解决方案


找到了。

我正确地尝试使用RelativeSource AncestorType,但寻找错误的控件。就我而言,当我使用 Telerik RadPanelBar 时,我需要搜索父 PanelBarPanel 控件...

RelativeSource={RelativeSource AncestorType={x:Type telerik:PanelBarPanel}}

这现在允许我访问对象的“ClearCommand”和“SearchCommand”属性,该对象也公开了“Criteria”属性。

找到它的方法是使用 Visual Studio 中的“LiveVisualTree”;我选择了一个绑定到“Criteria”对象属性的控件,然后沿着可视树向上走,同时密切关注每个祖先控件的“DataContext”属性,直到它与我的对象类型(类)匹配期待。


推荐阅读