Event handlers connected in XAML must be declared in code attached to the XAML file. In the case of ResourceDictionary or something downloaded from XamlReader.Load, there can be no code, so event handlers cannot be installed in XAML. The easiest way to get around this limitation would be to not create your template from strings and simply declare it in the Resources section of your XAML file, which you can do as follows:
Resources["MyTemplate"] as DataTemplate
to get the template and assign it in code like you are here, or just use StaticResource in XAML. As long as it remains in the same XAML file connected to this code, the event handlers that you have should now work fine. The dynamic portion of strings must also be modified to use Bindings.
If you want to stick with the XamlReader method, you have 2 problems to solve.
- Locate the ComboBox instance inside the generated template.
- Wait until the template is displayed to view the ComboBox
To find a ComboBox, you first need to assign it the x: Name attribute in the template text (you can simply replace the event code for the time being). Then you will need to find the element in the visual tree by name. It is quite simple, and here you can find it here .
To call this code at the right time, you need to either override OnApplyTemplate, which, unfortunately, will not work if you use something like UserControl, or use a different trick so that it does not work until all the controls are displayed. Here is a complete example that could go in the constructor and use the find method linked from above:
DataTemplate template = Resources["MyTemplate"] as DataTemplate; dynamicDataForm.ContentTemplate = template; Dispatcher.BeginInvoke(() => { ComboBox button = FindVisualChildByName<ComboBox>(this, "MyControl"); if (button != null) button.MouseLeftButtonUp += (s, _) => MessageBox.Show("Click"); });
In your case, it looks like your template may have to wait to go to the editing state before it displays, in which case you will need to disconnect when the event is connected and find some other event in your data form that will happen when the state is changed.
John bowen
source share