views:

392

answers:

1

I have a question related to this one: I'm trying to attach an event to my StackPanel but it doesn't appear to connect when using the XamlReader. I can't get the ChildItem_Load method to get called. Does anyone know of a way to do this?

Other than this event the code works fine.

this._listBox.ItemTemplate = (DataTemplate) XamlReader.Load(
                    @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""&gt;
                          <Border>
                              <StackPanel Loaded=""ChildItem_Loaded"">
                                  <TextBlock Text=""{Binding " + this._displayMemberPath + @"}"" />
                              </StackPanel>
                          </Border>
                      </DataTemplate>"
+2  A: 

Ok, I figured out a bit of a 'hack' solution, but it works.

Since it looks like the XamlReader doesn't have any knowledge of the local namespace when creating the DataTemplate I extended the StackPanel and "baked-in" the Load event. It's not exactly 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...
    }
}
Nick Gotch