使用可冻结命令
<Grid>
<Grid.DataContext>
<WpfApplication1:ViewModel />
</Grid.DataContext>
<Button Content="Text">
<Button.Command>
<WpfApplication1:MessageBoxCommand YesCommand="{Binding MyViewModelCommand}" />
</Button.Command>
</Button>
</Grid>
public class MessageBoxCommand : Freezable, ICommand
{
public static readonly DependencyProperty YesCommandProperty = DependencyProperty.Register(
"YesCommand",
typeof (ICommand),
typeof (MessageBoxCommand),
new FrameworkPropertyMetadata(null)
);
public static readonly DependencyProperty OKCommandProperty = DependencyProperty.Register(
"OKCommand",
typeof (ICommand),
typeof (MessageBoxCommand),
new FrameworkPropertyMetadata(null)
);
public static readonly DependencyProperty CancelCommandProperty = DependencyProperty.Register(
"CancelCommand",
typeof (ICommand),
typeof (MessageBoxCommand),
new FrameworkPropertyMetadata(null)
);
public static readonly DependencyProperty NoCommandProperty = DependencyProperty.Register(
"NoCommand",
typeof (ICommand),
typeof (MessageBoxCommand),
new FrameworkPropertyMetadata(null)
);
public static readonly DependencyProperty MessageProperty = DependencyProperty.Register(
"Message",
typeof (string),
typeof (MessageBoxCommand),
new FrameworkPropertyMetadata("")
);
public static readonly DependencyProperty MessageBoxButtonsProperty = DependencyProperty.Register(
"MessageBoxButtons",
typeof(MessageBoxButton),
typeof(MessageBoxCommand),
new FrameworkPropertyMetadata(MessageBoxButton.OKCancel)
);
public ICommand YesCommand
{
get { return (ICommand) GetValue(YesCommandProperty); }
set { SetValue(YesCommandProperty, value); }
}
public ICommand OKCommand
{
get { return (ICommand) GetValue(OKCommandProperty); }
set { SetValue(OKCommandProperty, value); }
}
public ICommand CancelCommand
{
get { return (ICommand) GetValue(CancelCommandProperty); }
set { SetValue(CancelCommandProperty, value); }
}
public ICommand NoCommand
{
get { return (ICommand) GetValue(NoCommandProperty); }
set { SetValue(NoCommandProperty, value); }
}
public MessageBoxButton MessageBoxButtons
{
get { return (MessageBoxButton)GetValue(MessageBoxButtonsProperty); }
set { SetValue(MessageBoxButtonsProperty, value); }
}
public string Message
{
get { return (string) GetValue(MessageProperty); }
set { SetValue(MessageProperty, value); }
}
public void Execute(object parameter)
{
var messageBoxResult = MessageBox.Show(Message);
switch (messageBoxResult)
{
case MessageBoxResult.OK:
OKCommand.Execute(null);
break;
case MessageBoxResult.Yes:
YesCommand.Execute(null);
break;
case MessageBoxResult.No:
NoCommand.Execute(null);
break;
case MessageBoxResult.Cancel:
if (CancelCommand != null) CancelCommand.Execute(null); //Cancel usually means do nothing ,so can be null
break;
}
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
protected override Freezable CreateInstanceCore()
{
throw new NotImplementedException();
}
}