0

関連する にアクセスするにはどうすればよいMenuItemですか? オンザフライで作成されているため、xaml ファイルの名前だけで使用することはできません。

private void menuItem_canExecute(object sender, CanExecuteRoutedEventArgs e)
{
    var snd = sender; // This is the main window
    var orgSource = e.OriginalSource; // This is a RichTextBox;
    var src = e.Source; // This is a UserControl

    // I think I must use the Command, but how?
    RoutedCommand routedCommand = e.Command as RoutedCommand;
}
4

2 に答える 2

1

CanExecuteRoutedEventArgsプロパティを持っていOriginalSourceます。

CanExecuteRoutedEventArgs の MSDN ドキュメント

OriginalSenderはおそらく の「TextBlock内側」にある になりMenuItemます。parentタイプの を見つけるために、ビジュアル ツリーをたどる必要があるでしょう。MenuItem

サンプルコードはこちらから

public static T GetVisualParent<T>(this DependencyObject child) where T : Visual
{
    //TODO wrap this in a loop to keep climbing the tree till the correct type is found 
    //or till we reach the end and haven't found the type
    Visual parentObject = VisualTreeHelper.GetParent(child) as Visual;
    if (parentObject == null) return null;
    return parentObject is T ? parentObject as T : GetVisualParent<T>(parentObject);
}

このように使用

var menuItem = e.OriginalSource.GetVisualParent<MenuItem>();
if (menuItem != null)
    //Do something....
于 2016-01-16T15:00:08.100 に答える