Attaching an Event Handler to a Code Generated DataTemplate

心已入冬 提交于 2019-12-03 17:24:40

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...
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!