Attaching an Event Handler to a Code Generated DataTemplate

谁都会走 提交于 2020-01-01 06:06:34

问题


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"">
                          <Border>
                              <StackPanel Loaded=""ChildItem_Loaded"">
                                  <TextBlock Text=""{Binding " + this._displayMemberPath + @"}"" />
                              </StackPanel>
                          </Border>
                      </DataTemplate>"

回答1:


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...
    }
}


来源:https://stackoverflow.com/questions/1650294/attaching-an-event-handler-to-a-code-generated-datatemplate

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