2016-01-16 36 views
0

我如何才能訪問相關的MenuItem?它已經實時創建,所以我不能僅僅通過xaml文件中的名稱來使用它。如何從CanExecute處理程序中獲取MenuItem?

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; 
} 
+1

您可以在菜單項的'CommandParameter'綁定到菜單項實例,比如'CommandParameter =「{綁定的RelativeSource = {的RelativeSource自} }並且可以通過CanExecuteRoutedEventArgs的'Parameter'屬性來訪問它。 – Clemens

+0

爲什麼你需要訪問'MenuItem'?也許有更好的方法來完成你想要做的事情。 – StillLearnin

+0

@Clemens:這是一個可行的解決方案,請將您的評論轉換爲答案。 – Pollitzer

回答

1

您可以隨時通過指揮UI元素綁定到它自己的CommandParameter屬性,如

<MenuItem ... CommandParameter="{Binding RelativeSource={RelativeSource Self}}"/> 

現在,您可以通過CanExecuteRoutedEventArgs的Parameter屬性訪問菜單項:

private void menuItem_canExecute(object sender, CanExecuteRoutedEventArgs e) 
{ 
    var menuItem = e.Parameter as MenuItem; 
    ... 
} 
1

CanExecuteRoutedEventArgsOriginalSource屬性。

MSDN Doc for CanExecuteRoutedEventArgs

OriginalSender可能會是一個TextBlock這是 「內部」 MenuItem。您可能需要遍歷視覺樹查找parent它的類型是從here

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); 
} 

MenuItem

示例代碼中使用這樣的

var menuItem = e.OriginalSource.GetVisualParent<MenuItem>(); 
if (menuItem != null) 
    //Do something.... 
+0

如果我在樹上搜索一個'MenuItem',我必須至少有一個不存在的獨特屬性。 – Pollitzer

+0

已更新我的回答,以便更清楚我建議您嘗試的內容。 – StillLearnin

+0

我試過你的建議,但在我的例子中'e.OriginalSource'是'RichTextBox'和'GetVisualParent (...)'總是返回null。 – Pollitzer

相關問題