WPF命令没有随机绑定

时间:2017-10-18 13:32:26

标签: c# wpf mvvm

我从WPF项目中看到了一些错误的代码。 ViewModelBase和RelayCommand类来自MVVM Light。这是子窗口的viewmodel类

class TOSelectionWindowViewModel : ViewModelBase
{
    ObservableCollection<ToElement> MyTo;

    public RelayCommand<ToAll> ToAddCmd { private set; get; }

    private Element selectedelement;
    public Element SelectedElement
    {
        get { return selectedelement; }
        set
        {
            if (value != selectedelement)
            {
                selectedelement = value;
                RaisePropertyChanged("SelectedElement");
            }
        }
    }

    public TOSelectionWindowViewModel(Element e)
    {
        SelectedElement = e;

        System.Console.WriteLine( object.ReferenceEquals(e, SelectedElement) ); // True
        System.Console.WriteLine(object.Equals(e, SelectedElement)); // True

        ToAddCmd = new RelayCommand<ToAll>((Added) =>
        {
        if (Added == null )
        {
            MessageBox.Show("COMMAND EXECUTED", "Message",
                         MessageBoxButton.OK, MessageBoxImage.Error);
               return;
            }
            using (ToElementEntities my = new ToElementEntities(@"Data Source = " + Globals.Directory + @"\DB\" + Globals.SelectedVessel.ID + @"\El_TO.db"))
            {
                my.ToElements.Add(new ToElement { ElementID = e.ID });
                my.SaveChanges();
                MyTo = new ObservableCollection<ToElement>(my.ToElements.Where(i => i.ElementID == SelectedElement.ID));
            }
        });
    }
}

此窗口显示如下:

TOSelectionWindow toselectionWindow = new TOSelectionWindow(SelectedElement);
//SelectedElement is a property of this VM
if (toselectionWindow.ShowDialog() == true)
{
    ...
}

问题是在打开和关闭这个子窗口后,ToAddCmd被执行或不被随机执行。 当我改变了

my.ToElements.Add(new ToElement { ElementID = e.ID });

my.ToElements.Add(new ToElement { ElementID = SelectedElement.ID });

它开始工作得很好甚至由于return语句而没有调用更正的代码行。你能解释一下为什么吗?

0 个答案:

没有答案