wpf - 如何正确绑定(bind)菜单项?

标签 wpf data-binding mvvm menuitem commandparameter

如何正确绑定(bind)动态创建的菜单项列表。我尝试了几件事,但似乎都不起作用。我得到了正确的名称列表,但是我的 ViewSwitchCommand 似乎没有正确触发。

<MenuItem Foreground="White" Header="Names" ItemsSource="{Binding Player.ToonNames}" Command="{Binding ViewSwitchCommand}" CommandParameter="{Binding Header}"/>

但是,如果我不动态地执行此操作并像这样执行操作,那么一切都会正常工作,可以使其正常工作

<MenuItem Foreground="White" Header="Names">
<MenuItem Foreground="Black" Header="Chat" Command="{Binding ViewSwitchCommand}"     CommandParameter="player1" />
<MenuItem Foreground="Black" Header="Craft" Command="{Binding ViewSwitchCommand}" CommandParameter="player2" />
</MenuItem>

命令参数需要一个字符串..不确定是否是这样...希望这是我刚刚忽略的简单内容

最佳答案

这段代码对我有用:

<MenuItem Header="Names" ItemsSource="{Binding Player.ToonNames}">
    <MenuItem.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Command" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MenuItem}, Path=DataContext.ViewSwitchCommand}" />
            <Setter Property="CommandParameter" Value="{Binding}" />
        </Style>
    </MenuItem.ItemContainerStyle>
</MenuItem>

关于wpf - 如何正确绑定(bind)菜单项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6246718/

相关文章:

c# - WPF 全局异常处理程序

android - DataBinding 在 Android Studio 2.3 中不起作用,无法转换为 android.databinding.tool.expr.StaticIdentifierExpr

silverlight - 谁在 Silverlight MVVM 中设置 DataContext

C# WPF GUI 性能 MVVM

c# - RelayCommand RaiseCanExecuteChanged() 失败

sql - 获取绑定(bind)在日历和组合框视频上的列表框

c# - 为 WPF 应用程序创建加载项

data-binding - MvxImageViewLoader 绑定(bind)不起作用

c# - CPU性能控制WPF

c# - XAML 内联数据绑定(bind)不起作用;绑定(bind)作品背后的代码