2011-11-08 38 views
0

我們在其子控件之一上有一個帶有上下文菜單的用戶控件。
命令綁定到ViewModel中的RelayCommand。
但是,該命令必須對View中的另一個子控件起作用。
這樣做的最好方法是什麼?我曾嘗試通過所需的子控件作爲參數,但我覺得語法不正確:SL4:將視圖中的元素作爲參數傳遞給ViewModel中的命令

     <Controls:ContextMenu > 
         <Controls:MenuItem Header="Center" > 
          <i:Interaction.Triggers> 
           <i:EventTrigger EventName="Click" > 
            <GalaSoft_MvvmLight_Command:EventToCommand 
             Command="{Binding RecenterCommand}" 
             CommandParameter="{Binding ElementName=scrollViewer}" /> 
           </i:EventTrigger> 
          </i:Interaction.Triggers> 
         </Controls:MenuItem> 
        </Controls:ContextMenu> 

命令:

RecenterCommand = new RelayCommand<ScrollViewer>(Recenter); 
private void Recenter(ScrollViewer obj) 
{ 
}  

當我使用上下文菜單,Recenter()被調用,但obj參數爲null。
CommandParameter綁定中的ElementName屬性的正確語法是什麼?

更新:我試圖改變CommandParameter到:

CommandParameter="{Binding ElementName=LayoutRoot, Path=scrollViewer}" 

...但仍然無法正常工作。

感謝任何見解....

+0

是你的元素其實x:Name = scrollViewer? – ecathell

+0

是的,它是: Number8

回答

0

我認爲你需要添加PassEventArgsToCommand =「真」,因此,該代碼將是這樣的:

<GalaSoft_MvvmLight_Command:EventToCommand PassEventArgsToCommand="True": 
            Command="{Binding RecenterCommand}" 
            CommandParameter="{Binding ElementName=scrollViewer}" /> 

,如果你想CATH在代碼隱藏把數據(這是從用於上下文菜單項我的節目之一代碼)

SelectedEmployer E =((菜單項)E).DataContext作爲僱主

我希望ŧ他會解決你的問題,因爲你給了我一個提示,如何解決我的一個問題..

+0

感謝您的回覆。當我使用RelayCommand 時,RoutedEventArgs.OriginalSource爲null。當我嘗試使用RelayCommmand 時,我無法使用PassEventArgsToCommand - 發生異常,說RoutedEventArgs無法轉換爲ScrollViewer。 – Number8

+0

如果我使用RelayCommand 和CommandParameter,則傳遞給該命令的ScrollViewer參數爲null。這讓我想知道CommandParameter中的語法是否不正確。 – Number8

相關問題