如何使用MVVM更新ContextMenu的ItemSource

时间:2017-09-14 12:01:04

标签: c# wpf mvvm contextmenu itemsource

我有一个ContextMenu,我试图从我的ViewModel类绑定一个列表。我使用两种不同的方法设置了这个List。更改时会触发OnZonesReceived方法,并且在选定的标签项更改时触发OnItemReceived方法。在这个项目中,我有tabItems,每个tabItem都有自己的DesignerCanvas。

问题是Zones在选定的选项卡项已更改时更新但在触发OnZonesReceived方法时更新DesignerCanvas时未更新,输入“canvas”具有正确的Zones列表。

ResouceDictionary

<MenuItem Header="Zones" ItemsSource="{Binding Zones, Mode=TwoWay}">
            <MenuItem.DataContext>
                <viewModel:ZoneViewModel/>
            </MenuItem.DataContext>
            <MenuItem.ItemTemplate>
                <DataTemplate DataType="{x:Type dataModel:ZoneModel}" >
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </MenuItem.ItemTemplate>
        </MenuItem>

视图模型

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using Core.Media;
using PropulsimGUI.Controls;
using PropulsimGUI.DataModel;
using PropulsimGUI.Utilities;

namespace PropulsimGUI.ViewModel
{
    public class ZoneViewModel : INotifyPropertyChanged
    {
        public ZoneViewModel()
        {
            Messenger.Default.Register<ClosableTab>(this, OnItemReceived);
            Messenger.Default.Register<DesignerCanvas>(this, OnZonesReceived, "Zone");
        }

        private void OnZonesReceived(DesignerCanvas canvas)
        {
            Zones = canvas.Zones;
        }

        public void OnItemReceived(ClosableTab item)
        {
            Zones = item.DesignerCanvas.Zones;
        }

        private List<ZoneModel> _zones;

        public List<ZoneModel> Zones
        {
            get { return _zones; }

            set
            {
                _zones = value;
                RaisePropertyChanged("Zones");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged(string propertyThatChanged)
        {
            //checking if event is not null than raise event and pass
            //in propperty name that has changed
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyThatChanged));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您提供的信息不足,但正如我所看到的,如果调用事件OnZonesReceived并且代码Zones = item.DesignerCanvas.Zones;有效,那么Zones = canvas.Zones;不起作用的唯一原因是{ {1}}是同一个对象,在这种情况下尽管绑定了canvas.Zones RaisePropertyChanged("Zones");将不会更新。即代码

Zones

不会更新ItemsSource。

您的解决方案可以是:

Zones.Add(new ZoneModel());
Zones=Zones;