将事件处理程序附加到代码生成的DataTemplate

Nic*_*tch 4 xaml datatemplate silverlight-3.0

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

除了这个事件,代码工作正常.

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>"
Run Code Online (Sandbox Code Playgroud)

Nic*_*tch 5

好吧,我想出了一个"黑客"解决方案,但它确实有效.

由于看起来XamlReader在创建DataTemplate时不了解本地命名空间,因此扩展了StackPanel并"烘焙"了Load事件.它不完全理想,但它有效:

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>"
    );
Run Code Online (Sandbox Code Playgroud)

和扩展类:

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

    private void ChildItem_Loaded(object sender, RoutedEventArgs e)
    {
        // Logic here...
    }
}
Run Code Online (Sandbox Code Playgroud)