带有触发器的网格示例:
<Grid x:Name="LayoutRoot" DataContext="{Binding ProjectGrid, Source={StaticResource Locator}}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding LoadedCommand, Mode=OneWay}" PassEventArgsToCommand="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
在我的 ViewModel 中,我将 LoadedCommand 设置为:
public RelayCommand<RoutedEventArgs> LoadedCommand {get;private set;}
在 ViewModel 初始化程序中,我有这个:
public ProjectGridViewModel()
{
LoadedCommand = new RelayCommand<RoutedEventArgs>(e =>
{
this.DoLoaded(e);
}
);
}
然后,在我的 DoLoaded 中,我试图这样做:
Grid _projectGrid = null;
public void DoLoaded(RoutedEventArgs e)
{
_projectGrid = e.OriginalSource as Grid;
}
您可以看到我正在尝试在我的视图中摆脱我的 Grid 中的 Loaded="",并改为执行 RelayCommand。问题是 OriginalSource 什么也没带回来。我加载的事件以这种方式运行良好,但我似乎需要通过 RoutedEventArgs 获取网格。
我尝试使用 CommandParameter="{Binding ElementName=LayoutRoot}" 在 EventCommand 中传递网格,但这只会在按下 F5 并运行项目时使 VS2010 崩溃。
有任何想法吗?或者更好的方法来做到这一点?我让 Loaded 事件在视图 C# 中运行,然后在视图代码隐藏中调用 ViewModel,但我想做一个更好的绑定。与 Views 代码隐藏中的 ViewMode 对话感觉就像是 hack。