使用正在初始化为参数的对象

时间:2016-06-30 09:08:09

标签: c# circular-reference object-initializers

我偶然发现了无法将windows方法用作对象初始值设定项内的属性的问题:

  var window = new DialogWindow
  {
    DataContext = new YesNoDialogViewModel()
    {
      DialogMessage = confirmation.Content as string,
      DialogTitle = confirmation.Title,
    }
  };

  (window.DataContext as YesNoDialogViewModel).CloseWindowCommand = new ActionCommand(window.Close);

我不想做这样的事情:

var window = new DialogWindow
  {
    DataContext = new YesNoDialogViewModel()
    {
      DialogMessage = confirmation.Content as string,
      DialogTitle = confirmation.Title,
      CloseWindowCommand = new ActionCommand(window.Close)
    }
  };

但是,我似乎无法弄明白(new ActionCommand(window.Close)没有编译,在声明之前无法使用窗口。)

是否有任何黑客或解决方法只是添加对void的引用?

1 个答案:

答案 0 :(得分:1)

你不能把它放在对象初始值设定项中,因为ActionCommand()在参数中使用了尚未创建的对象 - window - > window.Close()