我的主窗口ViewModel中有以下ICommand。
RelayCommand busyIndicatorCommand;
public ICommand BusyIndicatorCommand
{
get
{
if (busyIndicatorCommand == null)
busyIndicatorCommand = new RelayCommand(BusyIndicatorCommandExecute, CanBusyIndicatorCommand);
return busyIndicatorCommand;
}
}
在XAML中你有一个按钮时,从子视图调用这样的东西是一个简单的过程。
<Button Content="Press Me"
Command="{Binding DataContext.BusyIndicatorCommand, RelativeSource={RelativeSource AncestorType=Window}}"
CommandParameter="{Binding EnableIndicator}"/>
我想做同样的事情,除了我的ViewModel并且没有按钮。我该怎么做?
[编辑]最终解决方案
创建了一个新的类项目
namespace Libs_SharedCommands
{ public class Commands
{
public enum CommandType
{
BusyIndicator
}
public static RoutedCommand cmd_BusyIndicator = new RoutedCommand();
}
}
在我的用户控件视图模型中添加了对它的引用,并执行它。
namespace UserControls
{
class UserControlViewModel
{
public UserControlViewModel()
{
setBusyIndicator(true);
Task.Factory.StartNew(() =>
{
//Do stuff here
})
.ContinueWith(t =>
{
Application.Current.Dispatcher.Invoke(new Action(() => setBusyIndicator(false)));
});
}
private void setBusyIndicator(bool enable)
{
Libs_SharedCommands.Commands.cmd_BusyIndicator.Execute(enable, null);
}
}
}
最后将RoutedCommand处理程序添加到我的主窗口View中,View窗口又调用主窗口ViewModel。对此非常满意,MVVM仍然完好无损。
namespace Application
{
public partial class MainView
{
public MainView()
{
InitializeComponent();
CommandBinding cbBusyIndicator = new CommandBinding(Libs_SharedCommands.Commands.cmd_BusyIndicator, BusyIndicator_MainNavCmdExecute, MainNavCmdCanExecute);
this.CommandBindings.Add(cbBusyIndicator);
}
private void BusyIndicator_MainNavCmdExecute(object sender, ExecutedRoutedEventArgs e)
{
setCommand(Libs_SharedCommands.Commands.CommandType.BusyIndicator, e.Parameter);
}
private void MainNavCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void setCommand(Libs_SharedCommands.Commands.CommandType view_type, object parameter)
{
var viewModel = (MainViewModel)DataContext;
if (viewModel != null)
{
switch (view_type)
{
case Libs_SharedCommands.Commands.CommandType.BusyIndicator:
viewModel.ShowBusyIndicator = Convert.ToBoolean(parameter);
break;
default:
break;
}
}
}
}
}