我有一个 WPF 应用程序,它使用 Fody Commander 来简化向视图模型添加命令的过程。
但是我遇到了一个奇怪的问题,如果命令被初始化,传递给我的类的构造函数的值会影响。
在我看来,我有
public EditWindow(DataModel.Unit Unit)
{
model = new ViewModels.EditViewModel(Unit);
DataContext = model;
model.CloseAction = new Action(Close);
InitializeComponent();
}
在我的视图模型的构造函数中,我有以下内容(其中 EditUnit 是带有更改通知的公共属性)
[ImplementPropertyChanged]
public class EditViewModel
{
public DataModel.Unit EditUnit { get; set; }
public EditViewModel (DataModel.Unit Unit)
{
if (Unit == null)
{
EditUnit = new DataModel.Unit();
isnew = true;
} else
{
EditUnit = Unit;
}
}
[OnCommand("Close1")]
public void Close()
{
this.CloseAction();
}
[OnCommand("SaveAndClose1")]
public void SaveAndClose()
{
// Data validation here
if (isnew) Ctx.Units.Add(EditUnit);
Ctx.SaveChanges();
this.CloseAction();
}
[OnCommandCanExecute("SaveAndClose1")]
public bool SaveAndCloseCanExecute()
{
return <Data validation result>
}
}
如果创建我的视图,传入一个单元,一切都很好。如果创建我的视图,传入 null,命令似乎不会被初始化并保持为 null。
我为此撕毁了我的头发,现在我刚刚将新对象的创建转移到我创建视图的位置(所以我总是传递和对象,因此命令正常工作)
但我完全不明白为什么会发生这种情况。