gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:05:20 26 4
gpt4 key购买 nike

我有一个关于 this one 的问题:我正在尝试将一个事件附加到我的 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>"

最佳答案

好的,我想出了一些“黑客”解决方案,但它有效。

由于在创建 DataTemplate 时 XamlReader 看起来似乎对本地命名空间一无所知,因此我扩展了 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...
}
}

关于xaml - 将事件处理程序附加到代码生成的 DataTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1650294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com