wpf 如何使用 Viewmodel-first 从代码隐藏设置 viewmodel 属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14276343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set viewmodel property from code-behind using Viewmodel-first?
提问by l33t
In my WPF (4.0) application I'm using Viewmodel-firstpattern. Hence, my viewmodels are created first, then the views - using data templates. A working demo can be found here.
在我的 WPF (4.0) 应用程序中,我使用了Viewmodel-first模式。因此,首先创建我的视图模型,然后创建视图 - 使用数据模板。可以在此处找到工作演示。
Now, from within the created views (code-behind), I need to modify a property of the viewmodel. In a View-firstapproach, I would simply access a named viewmodel instance. However, the Viewmodel-firstapproach does not allow for this. There is a viewmodel, but the view does not care what it is.
现在,从创建的视图(代码隐藏)中,我需要修改视图模型的属性。在一种View-first方法中,我会简单地访问一个命名的视图模型实例。但是,该Viewmodel-first方法不允许这样做。有一个视图模型,但视图并不关心它是什么。
BAD:
坏的:
Sure you can get hold of the DataContextand use it, but that effectively couples the view and t
the viewmodel.
当然你可以得到DataContext并使用它,但这有效地耦合了视图和视图模型。
private void MyView_Loaded(object sender, RoutedEventArgs e)
{
this.viewModel = DataContext as MyViewModel;
}
There has to be a recommended pattern for this. Commands? Messages? Please help!
为此必须有一个推荐的模式。命令?消息?请帮忙!
Q: How do I modify (set a property) the active viewmodel?
问:如何修改(设置属性)活动视图模型?
采纳答案by Erno
Use Bindings to pass data from View to ViewModel and commands to active the ViewModel.
使用绑定将数据从 View 传递到 ViewModel,并使用命令激活 ViewModel。
Commands should use a binding to a execute a Command on the ViewModel.
命令应该使用绑定来在 ViewModel 上执行命令。
Messages should be used to communicate between ViewModels.
消息应该用于在 ViewModel 之间进行通信。
.
.
回答by Tilak
You can't do that. Otherwise View will be aware about View Model.
你不能那样做。否则 View 会知道 View Model。
If this initialization is common across all view models, then you can define the properties/events in ViewModelBaseand derive all view models from this class.
如果此初始化在所有视图模型中通用,那么您可以定义属性/事件ViewModelBase并从此类派生所有视图模型。
Q: How do I modify (set a property) the active viewmodel?
问:如何修改(设置属性)活动视图模型?
You need to use EventAggregatorpattern for View-ViewModel communication.
您需要使用EventAggregator模式进行 View-ViewModel 通信。
You can use your favorite MVVM framework, and nearly all framework support EventAggregator(or MessageBusor Enterprise Bus).
您可以使用您最喜欢的MVVM 框架,以及几乎所有框架支持EventAggregator(或MessageBus或Enterprise Bus)。

