Skip to main content
 首页 » 编程设计

c#之为什么我的 ObservableCollectionMenuItem> 不会在 RaisePropertyChanged 上更新

2024年02月23日21开发

在我的 WPF 应用程序中,我有一个 ObservableCollection<MenuItem>它会动态更新以包含各种类别项目。当屏幕加载时,一切都很好,但在屏幕打开时更改集合,并调用 RaisePropertyChanged对于集合不会更新上下文菜单。

似乎上下文菜单可能只在控件加载时加载并且不能动态更改?

更新:此代码根据用户添加或删除的项目动态创建子上下文菜单。我的问题是为什么在调用 RaisePropertyChanged 时不调用 DocumentExplorerMenuOptions getter?我看到 RaisePropertyChanged 被调用,但 setter/getter 从未被要求任何东西。

    public ObservableCollection<MenuItem> DocumentExplorerMenuOptions { 
        get { 
            return new ObservableCollection<MenuItem> {                      
                new MenuItem(localizationProvider.Takeoff) { 
                    Command = new DelegatingCommand(x => windowManager.ShowTakeoffWithGrid(context, selectedDocument, documentBagTasks)) 
                 }, 
                new MenuItem(localizationProvider.TakeoffImage) { 
                    Command = new DelegatingCommand(x => windowManager.ShowTakeoff(context, selectedDocument, documentBagTasks)) 
                 }, 
                 ClassificationMenuItem 
            }; 
        } 
    } 
 
    MenuItem classificationMenuItem; 
    public MenuItem ClassificationMenuItem { 
        get { return classificationMenuItem; } 
        set { classificationMenuItem = value; } 
    } 
 
    void BuildClassificationsContextMenuItem(ICategoryBag categoryBag) { 
        ClassificationMenuItem = new MenuItem(localizationProvider.ClassifyAs);  
 
        if (categoryBag == null) return; 
        foreach (var category in (from category in categoryBag.Categories select category).OrderBy(x => x.Name)) { 
            AddCategoryMenuItem(category); 
        } 
        RaisePropertyChanged(DocumentExplorerMenuOptionsPropertyName); 
    } 
 
    void RemoveCategoryMenuItem(Category category) { 
        ClassificationMenuItem.Children.RemoveAll(x => x.Text == category.Name); 
        RaisePropertyChanged(DocumentExplorerMenuOptionsPropertyName); 
    } 
 
    void AddCategoryMenuItem(Category category) { 
        var categoryMenuItem = new MenuItem(category.Name); 
        ClassificationMenuItem.Children.Add(categoryMenuItem); 
        foreach(var value in category.Values) { 
            categoryMenuItem.Children.Add(new MenuItem(value.Name) { Command = new DelegatingCommand(x => classifier.Classify(new ClassificationArguments(category, value, new List<Document>(documentExplorer.SelectedDocuments).ToArray()))) }); 
        } 
        RaisePropertyChanged(DocumentExplorerMenuOptionsPropertyName); 
    } 

请您参考如下方法:

ObservableCollection 属性设置不正确。您已将所有内容添加到该属性的 setter/getter 中,但这实际上不起作用。尝试创建一个私有(private)成员并在构造函数本身上实例化它,然后在其中添加这些条目。在这种情况下,您需要为每个 View 加载重新实例化 ObservableCollection,因为 getter 可能会被多次调用。