C# MVVM中的子菜单项选择
我使用以下XAML用最新文档填充子菜单项列表:C# MVVM中的子菜单项选择,c#,wpf,mvvm,menu-items,C#,Wpf,Mvvm,Menu Items,我使用以下XAML用最新文档填充子菜单项列表: <MenuItem Header="_Recent Studies" ItemsSource="{Binding RecentFiles}" AlternationCount="{Binding Path=Items.Count, Mode=OneWay,
<MenuItem Header="_Recent Studies"
ItemsSource="{Binding RecentFiles}"
AlternationCount="{Binding Path=Items.Count,
Mode=OneWay,
RelativeSource={RelativeSource Self}}"
ItemContainerStyle="{StaticResource RecentMenuItem}"/>
现在,它可以正常工作,并显示我最近的菜单项,如下所示:
我的问题是,我如何绑定到我最近的文件MenuItem
s上的单击事件?我可以使用AttachedCommands
,但我不知道如何实现这一点
谢谢您的时间。如果您使用的是MVVM模式,则根本不需要单击事件 您应该使用属性与ViewModel通信 怎么做? 如我所见,您正在使用ItemContainerStyle。可以将以下行添加到该样式:
<Style x:Key="RecentMenuItem" TargetType="MenuItem">
...
<Setter Property="Command" Value="{Binding Path=SelectCommand}" />
...
</Style>
您可以在
RecentFile
类的构造函数中初始化命令。是,但是如何初始化?这就是问题所在。我遇到问题的原因是这些项是在运行时填充的……啊,当然。愚蠢。但是,要使绑定从您需要的样式开始工作:
。谢谢你抽出时间。
<Style x:Key="RecentMenuItem" TargetType="MenuItem">
...
<Setter Property="Command" Value="{Binding Path=SelectCommand}" />
...
</Style>
public ICommand SelectCommand { get; private set; }