gpt4 book ai didi

c# - 如何在 viewmodel 中访问 mvvm 模型中的控件?

转载 作者:IT王子 更新时间:2023-10-29 04:08:57 26 4
gpt4 key购买 nike

我有一个 WPF 窗口,在那个窗口中我有一个网格。

我使用 M-V-VM 模型,我想在代码中(在 View 模型中)动态地向网格添加一个文本框

我怎样才能访问网格?

最佳答案

使用监督 Controller 模式。

阅读:

此处显示了 CaliburnMicro MVVM 框架的示例实现(对于所有其他框架同样适用 - 或者如果您自己执行 MVVM,则可以手动完成):

http://drc.ideablade.com/devforce-2012/bin/view/Documentation/cocktail-tutorial-talk-to-view

示例:

1) 定义接口(interface) 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()
}
}

关于c# - 如何在 viewmodel 中访问 mvvm 模型中的控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14236222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com