【发布时间】:2012-06-05 17:51:20
【问题描述】:
我仍在体验命令和路由事件。在不使用 RoutedCommands 的情况下,我尝试实现一个非常简单的程序。
这是我的命令类:
public class ColorChanger : ICommand
{
public static readonly RoutedEvent ChangeMyColor = EventManager.RegisterRoutedEvent("ChangeMyColor", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(ColorChanger));
public void Execute(object parameter)
{
RoutedEventArgs eventArgs = new RoutedEventArgs(ChangeMyColor);
Keyboard.FocusedElement.RaiseEvent(eventArgs);
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public static void AddChangeMyColorHandler(DependencyObject o, RoutedEventHandler handler)
{
((UIElement)o).AddHandler(ColorChanger.ChangeMyColor, handler);
}
public static void RemoveChangeMyColorHandler(DependencyObject o, RoutedEventHandler handler)
{
((UIElement)o).AddHandler(ColorChanger.ChangeMyColor, handler);
}
}
为了确保我对该命令具有静态访问权限,我创建了一个静态类来保存所有命令:
public static class AppCommands
{
private static ColorChanger colorChanger = new ColorChanger();
public static ColorChanger ColorChanger
{
get { return colorChanger; }
}
}
这是您将在我的 MainWindow.xaml 中找到的内容:
<StackPanel>
<Menu>
<MenuItem Command="{x:Static local:AppCommands.ColorChanger}" Header="ClickMe"
CommandTarget="{Binding ElementName=mainTextBox}" x:Name="menue1"/>
</Menu>
<TextBox Name="mainTextBox"/>
</StackPanel>
我想要的是通过单击 menue1-item 更改“mainTextBox”的背景。 那么让我们看看我的 MainWindow.cs 内部:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
AddHandler(ColorChanger.ChangeMyColor,new RoutedEventHandler(test));
}
public void test(object sender, RoutedEventArgs args)
{
Control someCtl = (Control) args.OriginalSource;
someCtl.Background = Brushes.BlueViolet;
}
}
该程序正在运行 - 但不正确 :) 它总是会更改 MainWindow 的背景,但不会更改我的 CommandTarget。
那么 - 我做错了什么? 我是不是忘记了什么?
【问题讨论】:
-
真的没有人可以帮忙吗?
-
虽然你的程序很简单,但是很难遵循。尝试更好地描述所需的行为。有帮助:您可以从MSDN 开始查看:“在 Windows Presentation Foundation (WPF) 命令系统中,ICommandSource 上的 CommandTarget 属性仅在 ICommand 是 RoutedCommand 时适用。如果 CommandTarget 设置在 ICommandSource 上并且对应的命令不是 RoutedCommand,命令目标被忽略。"
标签: wpf command icommand routedevent