如何访问在视图模型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.
我使用MV-VM模式,我想一个TextBox动态添加到网格在代码(在视图模型)
I use M-V-VM model and I want to add a TextBox to the grid dynamically in code(in viewmodel)
我如何获得接入电网?
推荐答案
不要使用由桑杰帕特尔提供的解决方案,您违反了整个MVVM目的,你将不能够测试代码即可。
Do not use solution provided by Sanjay Patel, you are violating whole MVVM purpose and you will not be able to test that code.
使用的监督控制器的模式。
Use Supervising Controller pattern.
< STRONG>阅读:
例实施的 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
在视图模型
( VM
)会跟查看
1) Define interface IView
in which ViewModel
(VM
) will talk to View
with required method(s)
public interface IView
{
void AddTextBoxToGrid()
}
2)的继承后面的代码查看
从 IVIEW
并实施 IView.AddTextboxToGrid()
法
public partial class View : IView
{
public void AddTextBoxToGrid()
{
// implement here your custom view logic using standard code behind;
}
}
3)添加型<物业code> IVIEW 你的 VM
3) Add property of type IView
to your VM
public class ViewModel
{
public IView View { get; set; }
}
4)设置查看
在 VM属性
来的视图实例
为 IVIEW
例如:在后面DataContext.View代码=本作的iView;还是在卡利可以使用IScreen.OnViewAttached覆盖方法)
4) Set View
property on VM
to instance of View
as IView
e.g. in code behind DataContext.View = this as IView; or in Caliburn you can use IScreen.OnViewAttached override method)
public partial class View : IView
{
public View()
{
// access you VM by 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()
}
}
这篇关于如何访问在视图模型MVVM模式控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!