Chỉ để tham khảo, lớp CommandReference hiện không được bao gồm trong một hội đồng mà bạn có thể tham chiếu, nhưng được bao gồm trong mẫu dự án M-V-VM. Vì vậy, nếu bạn không xây dựng ứng dụng của bạn từ các mẫu, sau đó bạn có để có được các lớp học từ một nơi khác. Tôi đã chọn để sao chép nó từ dự án mẫu. Tôi đã đưa nó vào bên dưới để cho phép mọi người dễ dàng truy cập vào phần nhỏ này của lòng tốt, nhưng hãy chắc chắn kiểm tra các bản cập nhật cho mẫu trong các phiên bản tương lai của Bộ công cụ M-V-VM.
/// <summary>
/// This class facilitates associating a key binding in XAML markup to a command
/// defined in a View Model by exposing a Command dependency property.
/// The class derives from Freezable to work around a limitation in WPF when data-binding from XAML.
/// </summary>
public class CommandReference : Freezable, ICommand
{
public CommandReference()
{
}
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandReference), new PropertyMetadata(new PropertyChangedCallback(OnCommandChanged)));
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
#region ICommand Members
public bool CanExecute(object parameter)
{
if (Command != null)
return Command.CanExecute(parameter);
return false;
}
public void Execute(object parameter)
{
Command.Execute(parameter);
}
public event EventHandler CanExecuteChanged;
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CommandReference commandReference = d as CommandReference;
if (commandReference != null)
{
ICommand oldCommand = e.OldValue as ICommand;
if (oldCommand != null)
oldCommand.CanExecuteChanged -= commandReference.CanExecuteChanged;
ICommand newCommand = e.NewValue as ICommand;
if (newCommand != null)
newCommand.CanExecuteChanged += commandReference.CanExecuteChanged;
}
}
#endregion
#region Freezable
protected override Freezable CreateInstanceCore()
{
return new CommandReference();
}
#endregion
}
Tận hưởng!
J, tôi không thể tìm thấy Freezable trong Silverlight, tôi thiếu gì? – kenny