假设我有以下内容:
<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,但是当用户在选择行时按下Enter键时我也想执行MyCommand(这意味着按钮不在焦点上)...
如何在WPF / MEF / PRISM中做到最好?
我认识到在代码中我无法将DataContext强制转换为(MyViewModel),因为这会违反MEF,而在后面的代码中我只知道viewmodel接口类型IViewModel ...
//code behind of the XAML file above
public IViewModel ViewModel
{
get;
set;
}
注意:我正在考虑在代码中执行此操作,但我不确定答案是否应该在viewmodel中执行...
答案 0 :(得分:1)
这可以使用KeyBindings完成。为您的Window创建一个新的KeyBidnign并将Command关联到它。 More information on KeyBindings
<ListBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding MyCommand}"/>
</ListBox.InputBindings>
viewmodel的CanExecute方法应该对Selected Row进行验证。
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; }
}