c# - 如何在 XAML 中创建 "Window"菜单?

标签 c# wpf xaml mvvm

我正在创建一个 MVVM Wpf 客户端应用程序。我想在主视图中为应用程序创建菜单,该应用程序上面有一个名为“Window”的菜单项。该菜单项将使用由应用程序中运行的事件窗口列表组成的菜单项子菜单动态更新自身。我创建了一个 ViewManager,每个 View 都向其注册自己以编译事件窗口列表。

我尝试在 XAML 中执行此操作,但在单击“窗口”时出现错误

<MenuItem Header="Window">
    <ItemsControl ItemsSource="{Binding ViewMgr.Views}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Title}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="MenuItem">
                <Setter Property="Command" Value="{Binding DataContext.OpenWindowCmd , 
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"/>
                <Setter Property="CommandParameter" Value="{Binding}"/>
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>
</MenuItem>

如何使用 MVVM 样式的数据绑定(bind)和命令在 XAML 中的菜单上创建动态更新的菜单项列表?

最佳答案

您正在添加一个新的 ItemsControl 作为菜单项的单个子项,而不是将每个 View 添加为菜单项本身的一个子项。您可能会收到错误消息,因为样式 TargetType 不匹配。 MenuItem 继承自 ItemsControl 本身并公开了一个属性 ItemsSource。尝试以下操作:

<MenuItem ItemsSource="{Binding ViewMgr.Views}" DisplayMemberPath="Title">

    <MenuItem.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Command" Value="{Binding DataContext.OpenWindowCmd,  RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"/>
            <Setter Property="CommandParameter" Value="{Binding}"/>
        </Style>
    </MenuItem.ItemContainerStyle>

</MenuItem>

关于c# - 如何在 XAML 中创建 "Window"菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21670585/

相关文章:

wpf - Application.Resources 中定义的样式不适用于控件

c# - xaml DataGrid 绑定(bind)到字典中的字典中的字典

c# - 在 C# 中从 Math.Sqrt 获取不同的输出

c# - ClosedXML 格式化单元格以包含公式

c# - 为什么 it.current 在调试期间改变他的值?

WPF文本框边框被选中时?

c# - 检测并处理应用程序突然结束任务、重启和关闭?

c# - 如何实现类似VS 2010的 float 选项卡?

c# - 覆盖 ComboBox 中的默认 TextBlock 样式

xaml - 转换器参数多绑定(bind)静态资源