![](/img/trans.png)
[英]RadBusyIndicator not showing PRISM/MEF/WPF from ViewModel
[英]Calling a command from item collection in 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,但是我也想在用户选择行时按下Enter键时执行MyCommand(这意味着按钮不在焦点上)...
如何在WPF / MEF / PRISM中做到最好?
我认识到在代码中我无法将DataContext强制转换为(MyViewModel),因为那样会违反MEF,而在后面的代码中,我仅知道viewmodel接口类型IViewModel ...
//code behind of the XAML file above
public IViewModel ViewModel
{
get;
set;
}
注意:我正在考虑在后面的代码中执行此操作,但是我不确定答案是否应该在viewmodel中执行...
可以使用KeyBindings完成。 在您的窗口中创建一个新的KeyBidnign并将一个Command与其关联。 有关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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.