我正在尝试使用EventToCommand来初始化我的ViewModel,但是命令没有触发。我怀疑这是因为触发器部分不在数据绑定容器中,但在我的示例中如何做到这一点呢?如果可能的话,我正试着坚持使用简单的XAML。
<Window x:Class="MVVMSample.Home"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:viewModels="clr-namespace:MVVMSample.ViewModels"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
d:DataContext="{d:DesignInstance Type=viewModels:HomeViewModel, IsDesignTimeCreatable=True}"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<viewModels:HomeViewModel x:Key="ViewModel" x:Name="ViewModel" />
</Window.Resources>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<cmd:EventToCommand Command="{Binding LoadedCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid DataContext="{StaticResource ViewModel}">
<TextBlock Text="{Binding PersonCount}" />
</Grid>
</Window> 发布于 2013-05-20 04:19:56
您说得对,数据上下文是问题的一部分,但我会按照设计使用mvvm-light来解决它。
如果您使用的是MVVM_Light,则应使用视图模型定位器。它是框架的主干。我使用mvvm light来学习mvvm原理。我非常喜欢它,因为它很简单,可以让我尽可能快地学习。
在mvvm-light中,您可以在app.xaml中声明视图模型定位器
<Application.Resources>
<ResourceDictionary>
<!--Global View Model Locator-->
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
</ResourceDictionary>
</Application.Resources> 然后在你的视图(可以是用户控件或者窗口等等)中,你可以将视图模型“附加”到你的视图中,如下所示:注意DataContext声明。
<UserControl x:Class="FTC.View.TrackingListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="http://www.galasoft.ch/mvvmlight"
mc:Ignorable="d"
DataContext="{Binding YourViewModel, Source={StaticResource Locator}}"
d:DesignHeight="700" d:DesignWidth="1000">这样,mvvm light中的视图模型定位器可以创建视图模型的单个实例,也可以根据需要创建唯一的实例。它还可以使用IOC将服务注入到视图模型的构造函数中。
因此,例如,如果我有一个处理来自数据模型的people对象的viewmodel,我创建了一个执行CRUD操作的people服务,然后在viewmodel构造函数参数中引用它。这允许我使用假的设计时数据或模型中的真实数据。它还保持了所有关注点的解耦,这就是mvvm的目的。
我建议阅读更多关于MVVM-light框架的内容,并从该网站构建一个样例。
See this video
希望这能有所帮助
https://stackoverflow.com/questions/16625341
复制相似问题