Attaching an Event Handler to DataTemplate Code Generated

I have a question related to this : I am trying to connect an event to my StackPanel, but it does not seem to connect when using XamlReader. I cannot get the ChildItem_Load method to call. Does anyone know a way to do this?

In addition to this event, the code works fine.

this._listBox.ItemTemplate = (DataTemplate) XamlReader.Load( @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> <Border> <StackPanel Loaded=""ChildItem_Loaded""> <TextBlock Text=""{Binding " + this._displayMemberPath + @"}"" /> </StackPanel> </Border> </DataTemplate>" 
+4
source share
1 answer

Ok, I decided to โ€œcrackโ€ the solution a bit, but it works.

Since it seems that XamlReader does not know about the local namespace when creating the DataTemplate, I expanded the StackPanel and โ€œbakeโ€ in the Load event. This is not entirely ideal, but it works:

 this._listBox.ItemTemplate = (DataTemplate) XamlReader.Load( @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:foo=""clr-namespace:Foo;assembly=Foo""> <Border> <foo:ExtendedStackPanel> <TextBlock Text=""{Binding " + this._displayMemberPath + @"}"" /> </foo:ExtendedStackPanel> </Border> </DataTemplate>" ); 

And the extended class:

 public class ExtendedStackPanel : StackPanel { public ExtendedStackPanel() : base() { this.Loaded += new RoutedEventHandler(this.ChildItem_Loaded); } private void ChildItem_Loaded(object sender, RoutedEventArgs e) { // Logic here... } } 
+5
source

All Articles