在WPF應用程序中有一個Grid
與一些對象(它們是從一個自定義控件派生的)。我想使用上下文菜單上的每個人執行一些動作:如何在WPF上下文中引用右鍵單擊的對象菜單項單擊事件處理程序?
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Name="EditStatusCm" Header="Change status" Click="EditStatusCm_Click"/>
</ContextMenu>
</Grid.ContextMenu>
但在事件處理程序我不能知道哪些對象是右鍵單擊:
private void EditStatusCm_Click(object sender, RoutedEventArgs e)
{
MyCustControl SCurrent = new MyCustControl();
MenuItem menu = sender as MenuItem;
SCurrent = menu.DataContext as MyCustControl; // here I get a run-time error
SCurrent.Status = MyCustControl.Status.Sixth;
}
在那個註釋行調試器說:未將對象引用設置爲對象的實例。
請幫忙,我的代碼有什麼問題?
編輯(添加):
我試圖做同樣的,使用命令方法:
我宣佈一個DataCommands
類具有RoutedUICommand Requery
,然後使用Window.CommandBindings
<Window.CommandBindings>
<CommandBinding Command="MyNamespace:DataCommands.Requery" Executed="RequeryCommand_Executed"></CommandBinding>
</Window.CommandBindings>
MenuItem的XAML現在看起來像:
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Name="EditStatusCm" Header="Change status" Command="MyNamespace:DataCommands.Requery"/>
</ContextMenu>
</Grid.ContextMenu>
和事件處理程序是這樣的:
private void RequeryCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
IInputElement parent = (IInputElement)LogicalTreeHelper.GetParent((DependencyObject)sender);
MyCustControl SCurrent = new MyCustControl();
SCurrent = (MuCustControl)parent;
string str = SCurrent.Name.ToString();// here I get the same error
MessageBox.Show(str);
}
但調試器顯示相同的運行時錯誤:對象引用不設置到對象的實例。
我的兩種方法都缺少什麼?
我應該如何引用在WPF上下文菜單項右鍵單擊事件處理程序?
我試着用命令的方式爲更多的WPF十歲上下,但得到了同樣的錯誤。我編輯了我的問題並添加了我的命令方法嘗試的步驟。我對如何獲得點擊的對象引用的理解在這兩種情況下都缺少一些東西 – rem 2010-01-09 11:50:17