开发者

How do you send in the LayoutRoot into a RelayCommand via a EventToCommand?

Grid example with the trigger:

<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>

In my ViewModel I set the LoadedCommand like this:

public RelayCommand<RoutedEventArgs> LoadedCommand {get;private set;}

And in the ViewModel initializer I have this:

public ProjectGridViewModel()
{
  LoadedCommand = new RelayCommand<RoutedEventArgs>(e => 
    {
      this.DoLoaded(e);
    }
  );
}

Then, in my DoLoaded I'm trying to do this:

Grid _projectGrid = null;
public void DoLoaded(RoutedEventArgs e)
{
  _projectGrid = e.OriginalSource as Grid;
}

You can see I'm trying to get rid of my Loaded="" in my Grid in my view, and do a RelayCommand instead. The issue is the OriginalSource brings back nothing. My loade开发者_运维技巧d event is running nice this way, but I need to get the Grid in via the RoutedEventArgs it seems.

I tried passing in the Grid in the EventCommand with CommandParameter="{Binding ElementName=LayoutRoot}", but this just crashes VS2010 when hitting F5 and running the project.

Any ideas? Or a better way to do this? I had the Loaded event run in the views C# then call the ViewModel in the Views code-behind, but I'd like to do a nicer binding. Talking to the ViewMode in the Views code-behind feels like a hack.


You could try to bind the CommandParameter of the EventToCommand:

<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding LoadedCommand, Mode=OneWay}" CommandParameter="{Binding ElementName=LayoutRoot}" PassEventArgsToCommand="True"/>

Then, your code will be:

public RelayCommand<UIElement> LoadedCommand {get;private set;} 

public ProjectGridViewModel() 
{ 
  LoadedCommand = new RelayCommand<UIElement>(e =>  
    { 
      this.DoLoaded(e); 
    } 
  ); 
} 

Grid _projectGrid = null; 
public void DoLoaded(UIElement e) 
{ 
  _projectGrid = e; 
} 

It should work fine :)

Bye.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜