我有以下 TreeView :
<TreeView Grid.Column="2" x:Name="itemTreeView" Margin="0" SelectedItemChanged="SelectionChanged">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:MarketGroup}">
<HierarchicalDataTemplate.ItemsSource>
<Binding Path="children"/>
</HierarchicalDataTemplate.ItemsSource>
<TextBlock Text="{Binding marketGroupName}" ToolTip="{Binding description}"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:ItemType}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding itemImage}" Height="{Binding Sibling.ActualHeight}"/>
<TextBlock Text="{Binding typeName}" ToolTip="{Binding description}"/>
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
所以我想要做的是将图像位于 DataTemplate 中,将其高度绑定(bind)到旁边 TextBlock 的实际高度,以便它们具有相同的大小。到目前为止,我所能找到的引用 sibling 的方法都依赖于定义 x:Name 并按名称引用它,但据我所知,我无法命名 DataTemplate 中的元素,因为它只是一个模板。或者,如果有办法将父 StackPanel 绑定(bind)到 TextBlock,然后将图像大小绑定(bind)到父级也应该可行(如果可能的话)。
最佳答案
TextBlock 中的
x:Name
,Binding 中的 ElementName
。
<Image
Source="{Binding itemImage}"
Height="{Binding ActualHeight, ElementName=SiblingTextBlock}"
/>
<TextBlock
x:Name="SiblingTextBlock"
Text="{Binding typeName}"
ToolTip="{Binding description}"
/>
谁告诉你这在 DataTemplate
中不起作用?您自然无法从模板外部引用该名称,因为实例化的模板实例可能有零个或多个。但在模板内就很好了。
关于c# - 如何绑定(bind)到DataTemplate中的同级元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42658056/