【问题标题】:How do you send in the LayoutRoot into a RelayCommand via a EventToCommand?如何通过 EventToCommand 将 LayoutRoot 发送到 RelayCommand?
【发布时间】:2010-05-21 02:06:49
【问题描述】:

带有触发器的网格示例:

<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 中传入 Grid,但这只会在按下 F5 并运行项目时导致 VS2010 崩溃。

有什么想法吗?或者更好的方法来做到这一点?我让 Loaded 事件在视图 C# 中运行,然后在视图代码隐藏中调用 ViewModel,但我想做一个更好的绑定。在 Views 代码隐藏中与 ViewMode 对话感觉就像是 hack。

【问题讨论】:

    标签: c# mvvm-light relaycommand


    【解决方案1】:

    你可以尝试绑定EventToCommand的CommandParameter:

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

    然后,您的代码将是:

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

    它应该可以正常工作:)

    再见。

    【讨论】:

    • 做到了。 Thx bud...lifesaver :) 我相信其他人也会想要这个,在搜索网络时找不到任何东西。
    猜你喜欢
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 2011-10-23
    • 2010-09-22
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多