将事件处理程序附加到代码生成的DataTemplate [英] Attaching an Event Handler to a Code Generated DataTemplate

查看:83
本文介绍了将事件处理程序附加到代码生成的DataTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与这个问题有关的问题:我正在尝试将事件附加到我的StackPanel上,但使用XamlReader时似乎没有连接。我无法调用ChildItem_Load方法。有人知道这样做的方法吗?

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>"


推荐答案

好吧,我发现了一些 hack解决方案,但是可以用。

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

因为看起来XamlReader在创建DataTemplate时不了解本地名称空间,所以我扩展了StackPanel并嵌入了Load ev耳鼻喉科。它并不完全理想,但可以正常工作:

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>"
    );

扩展类:

public class ExtendedStackPanel : StackPanel
{
    public ExtendedStackPanel() : base()
    {
        this.Loaded += new RoutedEventHandler(this.ChildItem_Loaded);
    }

    private void ChildItem_Loaded(object sender, RoutedEventArgs e)
    {
        // Logic here...
    }
}

这篇关于将事件处理程序附加到代码生成的DataTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆