2009-10-30 89 views
4

我有一个与this one有关的问题:我尝试将一个事件附加到我的StackPanel,但在使用XamlReader时它不会连接。我无法获取调用ChildItem_Load方法。有谁知道一种方法来做到这一点?将事件处理程序附加到代码生成的DataTemplate

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

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

回答

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

和扩展类:

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

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

尼斯的答案 - 谢谢! – edtheprogrammerguy 2013-05-23 20:39:10

相关问题