使用 Supervising Controller 模式。
阅读:
CaliburnMicro MVVM 框架的示例实现如下所示(对所有其他框架都一样——或者如果你自己做 MVVM,你也可以手动做):
http://drc.ideablade.com/devforce-2012/bin/view/Documentation/cocktail-tutorial-talk-to-view
示例:
1) 定义接口IView,其中ViewModel (VM) 将使用所需的方法与View 对话
public interface IView
{
void AddTextBoxToGrid();
}
2) 从你的IView继承View后面的代码并实现IView.AddTextboxToGrid()方法
public partial class View: IView
{
public void AddTextBoxToGrid()
{
// implement here your custom view logic using standard code behind;
}
}
3) 将IView 类型的属性添加到您的VM
public class ViewModel
{
public IView View { get; set; }
}
4) 将VM 上的View 属性设置为View 的实例 为IView
例如在后面的代码中:
DataContext.View = this as IView;
或者在 Caliburn 中你可以使用 IScreen.OnViewAttached 覆盖方法)
public partial class View: IView
{
public View()
{
// access you VM by the strategy of your framework or choice - this example is when you store your VM in View's DataContext
(DataContext as ViewModel).View = this as IView;
}
public void AddTextBoxToGrid()
{
// implement here your custom view logic using standard code behind;
}
}
5) 在您的VM 致电IView.AddTextboxToGrid()
public class ViewModel
{
public IView View { get; set; }
public void AddTextBoxToGrid()
{
if (View == null) return;
View.AddTextBoxToGrid()
}
}