如何使用 MVVM 在代码中添加新网格到网格中
如何动态地将一个网格添加到另一个网格中?我不能这样做:
myGrid.Children.Add(dg);
因为我没有这个网格的实例 - 我正在使用 MVVM。
请帮忙。
How can I add dynamically a grid into another grid? I can't do this:
myGrid.Children.Add(dg);
Because I don't have the instance of this grid - I'm using MVVM.
Please Help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设,既然你提到了 MVVM,你想从你的视图模型中完成这个任务吗?
在这种情况下,我的建议是从视图模型向视图发送消息。
在视图中,您添加对此消息的订阅并从那里添加网格。
你可以用最简单的形式来做这样的事情。这将使用优秀的 MVVM Light 框架:
ViewModel.cs:
<代码>View.xaml.cs:
I assume, since you mention MVVM, that you want to accomplish this from your View Model?
In that case my suggestion is to send a message from the View Model to the View.
In the View you add a subscription to this message and add the Grid from there.
You could do it something like this, in its most simple form. This would be using the excellent MVVM Light framework:
ViewModel.cs:
View.xaml.cs:
如果您在运行时动态添加控件,简短的回答是您可能无法通过 MVVM 成功做到这一点。将其放入代码隐藏中可能是您最好的选择——在不知道您正在构建什么类型的应用程序的情况下,很难做出判断并大声要求您必须使用 MVVM。
话虽这么说,我很少发现自己遇到 WPF 中必须进行此类动态控制操作的情况。相反,我最终使用不同的 WPF 构造(ListBox、ContentControl、ItemsControl 等)以及 ItemTemplates 等内容来获得我想要的内容。
同样,如果不更多地了解您想要完成的任务,就很难提供任何类型的规范性指导。
If you're dynamically adding controls at runtime, the short answer is that you probably aren't going to be successful doing that via MVVM. Dropping that into the codebehind may be your best bet-- without knowing what kind of app you're building, it is hard to pass judgement and demand loudly that you MUST use MVVM.
That being said, I rarely find myself in a situation with WPF where I have to do dynamic control manipulation like that. Instead, I wind up using different WPF constructs (ListBox, ContentControl, ItemsControl, etc.), along with things like ItemTemplates to get what I want.
Again, without knowing more about what you're trying to accomplish, it's difficult to give any kind of prescriptive guidance.