如何在 viewmodel 中访问 mvvm 模型中的控件? [英] How can i access a control in mvvm model in viewmodel?
问题描述
我有一个 WPF 窗口,在那个窗口中我有一个网格.
I have a WPF Window, and in that window I have a grid.
我使用 M-V-VM 模型,我想在代码中(在视图模型中)动态地将一个文本框添加到网格中
I use M-V-VM model and I want to add a TextBox to the grid dynamically in code(in viewmodel)
如何访问网格?
推荐答案
使用监督控制器模式.
Use Supervising Controller pattern.
阅读:
此处显示了 CaliburnMicro MVVM 框架的示例实现(适用于所有其他框架 - 或者如果您自己执行 MVVM,则可以手动完成):
Example implementation for CaliburnMicro MVVM framework is shown here (will work same for all other frameworks - or you can do it by hand if you are doing MVVM by yourself):
http://drc.ideablade.com/devforce-2012/bin/view/Documentation/cocktail-tutorial-talk-to-view
示例:
1) 定义接口IView
,其中ViewModel
(VM
) 将与View
使用所需的方法
1) Define interface IView
in which ViewModel
(VM
) will talk to View
with the required method(s)
public interface IView
{
void AddTextBoxToGrid();
}
2) 从你的 IView
继承 View
后面的代码并实现 IView.AddTextboxToGrid()
方法>
2) Inherit code behind View
from your IView
and implement IView.AddTextboxToGrid()
method
public partial class View: IView
{
public void AddTextBoxToGrid()
{
// implement here your custom view logic using standard code behind;
}
}
3) 将 IView
类型的属性添加到您的 VM
3) Add a property of type IView
to your VM
public class ViewModel
{
public IView View { get; set; }
}
4) 将 VM
上的 View
属性设置为 View
的一个实例为 IView代码>例如在后面的代码中:
4) Set View
property on VM
to an instance of View
as IView
e.g. in code behind:
DataContext.View = this as IView;
或者在 Caliburn 中你可以使用 IScreen.OnViewAttached 覆盖方法)
or in Caliburn you can use IScreen.OnViewAttached override method)
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()
5) In your VM
call IView.AddTextboxToGrid()
public class ViewModel
{
public IView View { get; set; }
public void AddTextBoxToGrid()
{
if (View == null) return;
View.AddTextBoxToGrid()
}
}
这篇关于如何在 viewmodel 中访问 mvvm 模型中的控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!