如何使用x:Reference动态生成MenuItems

本文关键字:MenuItems 动态 Reference 何使用 | 更新日期: 2023-09-27 18:25:35

我有一个MenuItem,其ItemsSource设置为以下CompositeCollection:

<CompositeCollection>
    <MenuItem x:Name="SpinnerMenuItem" Header="Waiting..."/>
    <CollectionContainer 
        Collection="{Binding DataContext.Source, 
                     Source={x:Reference SpinnerMenuItem}, 
                     Converter={StaticResource NoOpConverter}}"/>
</CompositeCollection>

NoOpConverter中的断点告诉我,我的集合已成功绑定到CollectionContainer。问题是,菜单显示完全为空!我得到的只是一个大约3像素高和10像素宽的弹出窗口。

为什么我的菜单项没有显示填充绑定列表后,甚至"SpinnerMenuItem"也会消失。在更简单的情况下,当我刚刚绑定到CollectionViewSource静态资源时,我没有遇到这个问题。

如何使用x:Reference动态生成MenuItems

这似乎是CompositeCollection的问题。解决方法是使用StaticResource,而不是Binding或类似的方法。更多信息请点击此处:为什么CompositeCollection不可冻结?