gpt4 book ai didi

c# - UserControl 中的 ContentPresenter

转载 作者:太空狗 更新时间:2023-10-29 18:08:34 33 4
gpt4 key购买 nike

我是 WPF 的新手,我正在尝试创建一个包含一些嵌套内容的 UserControl。

<my:InformationBox Header="General Information" Width="280">
<StackPanel>
<Label>Label1</Label>
<Label>Label2</Label>
</StackPanel>
</my:InformationBox>

如您所见,我想将 StackPanel 放入其中。当我阅读一些文章时,我应该将 ContentPresenter 添加到我的 UserControl,我确实这样做了,但是我找不到应该绑定(bind)到它的 Content 属性的内容。

这是我的用户控件代码

<UserControl x:Class="ITMAN.InformationBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="200" d:DesignWidth="280" Name="infoBox" Loaded="infoBox_Loaded">
<StackPanel Width="{Binding ElementName=infoBox, Path=Width}" HorizontalAlignment="Stretch">
<Label Content="{Binding ElementName=infoBox, Path=Header}" />
<Border BorderThickness="0,1,0,0" Padding="10 5" Margin="5 0 5 10" BorderBrush="#B4CEDE">
<StackPanel>
<ContentPresenter Content="{Binding Content}" />
<Label Content="End" />
</StackPanel>
</Border>
</StackPanel>
</UserControl>

我尝试了各种文章中的许多组合,但我找不到任何我想要实现的工作示例。

另一个用户早些时候问过类似的问题,但给出的答案对我没有帮助:Does anyone have a simple example of a UserControl with a single ContentPresenter?

最佳答案

ContentPresenter 是一种魔法控件。如果您不提供任何内容,它会自动设置 ContentContentTemplateContentTemplateSelector 属性以及 TemplateBinding 到 TemplatedParent。这意味着,您不需要向它提供任何东西,只需

<ContentPresenter/>

在您的 UserControl 中,它应该自动使用在您的 UserControl 中找到的相应属性。还请记住,像 {Binding Content} 这样的绑定(bind)总是引用您的 DataContext,我猜这不是您想要的。

关于c# - UserControl 中的 ContentPresenter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11558298/

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