我仍然在使用Commands和RoutedEvents的經驗。沒有使用RoutedCommands,我嘗試實現一個簡單的程序。我在哪裏可以找到CommandTarget?
這裏是我的命令類:
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;
}
}
的PROGRAMM工作 - 但不是正確的:)它總是改變主窗口的背景,但不是我的CommandTarget的。
所以 - 我做錯了什麼? 我忘了什麼嗎?
真的沒人在這裏誰可以幫忙? – CodeCannibal
雖然你的程序很簡單,但很難遵循。嘗試描述更好的理想行爲。要有所幫助:您可以從這裏開始查看[MSDN](http://msdn.microsoft.com/zh-cn/library/system.windows.input.icommandsource.commandtarget.aspx):「在Windows Presentation Foundation( WPF)的命令系統,ICommandSource上的CommandTarget屬性只適用於ICommand是RoutedCommand的情況,如果CommandTarget設置在ICommandSource上,並且相應的命令不是RoutedCommand,則命令目標將被忽略。 – nemesv