简体   繁体   English

WPF在菜单显示之前更新上下文菜单项

[英]WPF update context menu items before menu display

I'm using WPF with Caliburn and the MVVM pattern and I'm trying to set up a dynamic context menu. 我正在使用带有Caliburn和MVVM模式的WPF,并且正在尝试设置动态上下文菜单。

Currently we have a context menu with it's Items bound to a BindableCollection on the ViewModel. 当前,我们有一个上下文菜单,其菜单项绑定到ViewModel上的BindableCollection。

<UserControl.ContextMenu>
         <ContextMenu ItemsSource="{Binding AvailableActions}"
                      actions:Action.TargetWithoutContext="{Binding}"
                      ItemContainerStyleSelector="{StaticResource NamedActionStyleSelector}"/>
</UserControl.ContextMenu>
public BindableCollection<NamedAction> AvailableActions { get; set; }

This BindableCollection is updated in certain circumstances during the running of the program by the method (Again on the view model): 此BindableCollection在某些情况下会在程序运行期间通过方法(在视图模型上再次)进行更新:

private void UpdateAvailableActions()

The current system works well for most situations but there are a few edge cases that suggest that we would be better served to dynamically generate the list after a right click event. 当前的系统在大多数情况下都可以正常工作,但是有一些边缘情况表明我们可以更好地在右键单击事件后动态生成列表。

So my question is, can anyone help me with the best way to call the update method (or write an alternative method which would be called) when the user has right clicked. 所以我的问题是,当用户右键单击时,有人能帮助我以最佳方式调用update方法(或编写将被调用的替代方法)的最佳方法。 Any help with how to do this would be greatly appreciated. 任何帮助如何做到这一点将不胜感激。

Thanks 谢谢

Personally, I'm a big fan of using OnPropertyChanged() from IPropertyNotifyChanged . 我个人非常喜欢使用IPropertyNotifyChanged OnPropertyChanged() This way you can create a command that gets executed on right clicking that calls OnPropertyChanged() . 这样,您可以创建一个在右键单击时执行的命令,该命令调用OnPropertyChanged() You will have to do a little research yourself about how you want to implement events as commands since you're using MVVM, a starting point can be found here or here . 由于您正在使用MVVM,因此您将需要做一些自己的研究,以了解如何将事件实现为命令,可以在此处此处找到起点。 Alternatively, you can get creative with the CommandParameter binding and use that in your command. 或者,您可以通过CommandParameter绑定获得创意,并在命令中使用它。

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM