I have an ItemsControl defined as shown below. Basically, I have a list of editors (EditorList) and I want hyperlinks for each. However, my open command (OpenEditorCommand) property is at the same level as the list of editors. How do I refer to that property when the context is set to the item within the list. I've tried working with the RelativeSource method but it's too convoluted for me to understand. Am I on the right track?
我有一个ItemsControl定义如下所示。基本上,我有一个编辑器列表(EditorList),我想要每个的超链接。但是,我的open命令(OpenEditorCommand)属性与编辑器列表处于同一级别。当上下文设置为列表中的项目时,如何引用该属性。我尝试过使用RelativeSource方法,但是对我来说理解起来太复杂了。我是在正确的轨道上吗?
<ItemsControl ItemsSource="{Binding EditorList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Margin="2,6" HorizontalAlignment="Center">
<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl, AncestorLevel=2, Mode=FindAncestor}, Path=OpenEditorCommand}" CommandParameter="{Binding Name}">
<StackPanel>
<Image Source="{Binding Image}" Width=32/>
<TextBlock Text="{Binding Path=Name}"/>
</StackPanel>
</Hyperlink>
</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
1 个解决方案
#1
4
You only need to set the AncestorLevel
in cases where there is possibly more than one ancestor of the searched type existing in the element tree. The default value is 1 which mean find the closest.
只有在元素树中存在可能有多个搜索类型的祖先的情况下,才需要设置AncestorLevel。默认值为1表示找到最接近的值。
But you need to specify in the Path
that you want to bind to the OpenEditorCommand
on the DataContext
of the ItemsControl
:
但是您需要在Path中指定要绑定到ItemsControl的DataContext上的OpenEditorCommand:
Command="{Binding Path=DataContext.OpenEditorCommand, RelativeSource={RelativeSource AncestorType=ItemsControl, Mode=FindAncestor}}"
#1
4
You only need to set the AncestorLevel
in cases where there is possibly more than one ancestor of the searched type existing in the element tree. The default value is 1 which mean find the closest.
只有在元素树中存在可能有多个搜索类型的祖先的情况下,才需要设置AncestorLevel。默认值为1表示找到最接近的值。
But you need to specify in the Path
that you want to bind to the OpenEditorCommand
on the DataContext
of the ItemsControl
:
但是您需要在Path中指定要绑定到ItemsControl的DataContext上的OpenEditorCommand:
Command="{Binding Path=DataContext.OpenEditorCommand, RelativeSource={RelativeSource AncestorType=ItemsControl, Mode=FindAncestor}}"