I faced the problem exactly as described in Setting event handlers inside a Setter.Value structure. But I want to understand why the solution provided by the question's author doesn't work. It looks like I missed some concept.
相关问题
- VNC control for WPF application
- How to stylize text in an alert box? [duplicate]
- Stop child process when parent process stops
- Fire resize event once not based on timing
- WPF Binding from System.Windows.SystemParameters.P
This appears to be a bug in the generation of the XAML code-behind. In addition to the user code-behind for XAML files, there is a "compiler" generated version that defines InitializeComponent and class fields for named elements (i.e. x:Name).
Given a simple example:
If you run this, you will get the following exception:
The generated code-behind files can be found in the
obj
folder, so if we examine that we can see the following code:The issue here is the code generated is trying to cast the
MenuItem
to aButton
. If we alter our sample like so:Then the code generated is:
Based on my tests, it appears the code generator assigns an ID to each control that it needs to "connect" or add handlers/backing fields for. In the case where the ContextMenu is included inline (i.e. the first example), it's event handlers are getting assigned to the root element inside the window and is not getting an ID of it's own.
If we changed Button to be contained in a Grid, then the exception above would indicate it failed to cast MenuItem to a Grid. Because now the Grid is the root element. This indicates it has nothing to do with the type the Style targets.
When the ContextMenu is included as a separate resource, the code generator seems to properly assign it an ID so it's handlers can be properly attached.
Ultimately, this is a bug in the XAML code generator.