2014-12-05 36 views
0

假設我有以下幾點:單擊該按鈕時調用從項目集合的命令,PRISM/MEF/WPF

<Grid x:Name="root"> 
    <ListBox ItemsSource="{Binding Path=Items}"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
      <DockPanel> 
       <Button Command="{Binding ElementName=root, Path=DataContext.MyCommand}" /> 
       <!---There are other UI elements here --> 
       </DockPanel/> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</Grid> 

此代碼執行mycommand的,但我也希望,當用戶按下回車鍵執行mycommand的當行被選中時鍵(這意味着按鈕不在焦點)...

如何在WPF/MEF/PRISM中做到最好?

我承認,在我的代碼無法施展DataContext的到(MyViewModel),因爲這將違反MEF,並在後面的代碼我只知道視圖模型接口類型IViewModel ...

//code behind of the XAML file above 
public IViewModel ViewModel 
{ 
    get; 
    set; 
} 

注意:我正在考慮在代碼背後這樣做,但我不確定答案是否應該在視圖模型中執行...

回答

1

這可以使用KeyBindings完成。爲您的窗口創建一個新的KeyBidnign並將命令與它關聯。 More information on KeyBindings

<ListBox.InputBindings> 
    <KeyBinding Key="Enter" Command="{Binding MyCommand}"/> 
</ListBox.InputBindings> 

您的viewmodel的CanExecute方法應該有一個選定行的驗證。

public class ViewModel 
{ 
    public ViewModel() 
    { 
     MyCommand = new DelegateCommand(MyCommandExecute, MyCommandCanExecute); 
    } 

    private void MyCommandExecute() 
    { 
     // Do your logic 
    } 

    private bool MyCommandCanExecute() 
    { 
     return this.SelectedRow != null; 
    } 

    public object SelectedRow { get; set; } 

    public DelegateCommand MyCommand { get; set; } 
} 
+0

我在窗口中有其他元素,而不僅僅是列表框,用戶可以在其中按下按鍵(這是有效的場景)。在你的例子中,這意味着窗口上的inputbindings會捕獲窗口右邊的所有Enter鍵?如果我只想抓住行中的Enter鍵,該怎麼辦? (在我的窗口中,實際上有很多可能的關鍵相互作用,這就是爲什麼我想盡可能具體地指出我在哪裏捕捉事件,但不僅如此,我正在尋找最適合PRISM的解決方案) – 2014-12-05 06:10:05

+0

..或我應該把InputBindings作爲ListBox嗎?... – 2014-12-05 06:11:57