【发布时间】:2013-09-17 12:55:26
【问题描述】:
我在资源字典中有以下MenuItem 模板
<Style x:Key="RecentMenuItem"
TargetType="{x:Type MenuItem}"
BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource
Mode=FindAncestor, AncestorType=MenuItem}, Path=DataContext.LoadRecentItemCommand}" />
<Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Header}"/>
<Setter Property="HeaderTemplate" >
<Setter.Value>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}. {1}">
<Binding Path="(ItemsControl.AlternationIndex)"
RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type MenuItem}}"/>
<Binding Path="FullFileName"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
这样使用
<Menu>
<MenuItem Header="FILE">
...
<MenuItem Header="_Recent Studies"
ItemsSource="{Binding RecentFiles}"
AlternationCount="{Binding Path=Items.Count,
Mode=OneWay,
RelativeSource={RelativeSource Self}}"
ItemContainerStyle="{StaticResource RecentMenuItem}"/>
<MenuItem/>
Command 上的绑定不起作用(我可以通过 Snoop[dog] 看到这一点)。
上述命令绑定有什么问题,如何解决?
感谢您的宝贵时间。
【问题讨论】:
-
也许您需要删除
Header="_Recent Studies"或者您需要绑定到HeaderTemplateEDIT 或FullFileName -
如果你想点击子
MenuItems,那么你肯定需要将CommandBehaviour对象添加到它们,而不是它们的父项? -
@Sheridan 我在问题的 PS 中尝试过这种方法。由于某种原因,这甚至不会触发!?
-
@Killercam 孩子需要绑定到父母的 DataContext 才能访问
LoadRecentItemCommand和Header... 你在这样做吗? -
@nmclean 我想我和
<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MenuItem}, Path=DataContext.LoadRecentFileCommand}" /> <Setter Property="CommandParameter" Value="{Binding}" />
标签: wpf binding command menuitem