gpt4 book ai didi

wpf - 为 ItemsControl.ItemContainerStyle 指定 ControlTemplate

转载 作者:行者123 更新时间:2023-12-03 11:48:43 25 4
gpt4 key购买 nike

以下类似于我要完成的工作。但是,我得到了错误

Invalid PropertyDescriptor value.



在模板上 Setter .我怀疑这是因为我没有指定 TargetType对于 Style ;但是,我不知道 ItemsControl 的容器类型.
<ItemsControl>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<StackPanel>
<TextBlock Text="Some Content Here" />
<ContentPresenter />
<Button Content="Edit" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.ItemContainerStyle>
<!-- heterogenous controls -->
<ItemsControl.Items>
<Button Content="Content 1" />
<TextBox Text="Content 2" />
<Label Content="Content 3" />
</ItemsControl.Items>
</ItemsControl>

最佳答案

您可以使用类型名称限定属性名称:

<Setter Property="Control.Template">
ItemsControl 的容器通常是 ContentPresenter , 但如果 child 是 UIElement那么它就不会使用容器。在这种情况下,所有的 child 都是控件,所以 ItemContainerStyle将直接适用于他们。如果您添加了 UIElement 以外的项目,该 setter 将设置 Control.Template ContentPresenter 上的属性(property),这会成功但没有效果。

实际上,听起来您想要的是将每个 child 包装在一个容器中,即使它们已经是 UIElement .为此,您必须使用 ItemsControl 的子类。 .您可以使用现有的 ListBox , 或者你可以继承 ItemsControl并覆盖 GetContainerForItemOverride IsItemItsOwnContainerOverride 将元素包装在您自己的容器中。您可以将它们包装在 ContentControl 中然后将其用作 TargetType对于 Style .
public class CustomItemsControl
: ItemsControl
{
protected override DependencyObject GetContainerForItemOverride()
{
return new ContentControl();
}

protected override bool IsItemItsOwnContainerOverride(object item)
{
// Even wrap other ContentControls
return false;
}
}

您还需要设置 TargetTypeControlTemplate使 ContentPresenter将绑定(bind)到 Content属性(property):
<ControlTemplate TargetType="ContentControl">

关于wpf - 为 ItemsControl.ItemContainerStyle 指定 ControlTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3542381/

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