gpt4 book ai didi

c# - 模板控件中的 ContentPresenter 不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 22:38:31 25 4
gpt4 key购买 nike

我已经创建了一个模板化控件。我对默认样式所做的只是添加一个内容展示器。我还在 App.xaml 文件中引用了 Generic.xaml。

<Style TargetType="local2:TestingControl" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local2:TestingControl">
<Border
Height="200px"
Background="Green">

<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


public sealed class TestingControl : Control
{
public TestingControl()
{
this.DefaultStyleKey = typeof(TestingControl);
}

}

我没有对控件的 .cs 代码进行任何更改。我尝试设置内容,但被告知该控件不允许直接内容。

 <StackPanel>
<local1:TestingControl >
Testing
</local1:TestingControl>

</StackPanel>

enter image description here我应该如何使用内容展示器?

如果我尝试使用用户控件,同样的方法非常有效。

最佳答案

要处理自定义模板化控件中的 XAML 内容,您必须从 ContentControl 派生控件。或者继续继承自 Control , 实现自定义 ContentProperty并绑定(bind) ContentPresenter

使用 ContentControl 更容易一些,下面是您可能最终得到的代码。

Themes/Generic.xaml 中的样式定义

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local="using:SmallTests2018">

<Style TargetType="local:TemplatedControlWithContent" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:TemplatedControlWithContent">
<Border
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Viewbox>
<Grid>
<Viewbox HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Ellipse Width="10" Height="10" Fill="#80808080" />
</Viewbox>
<ContentPresenter />
</Grid>
</Viewbox>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
  • 我更喜欢将 Border 绑定(bind)到模板化控件属性,这样使用它的开发人员可以更好地控制外观。
  • 此处的椭圆是一些额外自定义内容的示例。

TemplatedControlWithContent.cs

using System;
using Windows.UI.Xaml.Controls;

namespace SmallTests2018
{
public sealed class TemplatedControlWithContent : ContentControl
{
public TemplatedControlWithContent()
{
DefaultStyleKey = typeof(TemplatedControlWithContent);
}
}
}
  • 请注意,此处唯一的变化是控件派生自 ContentControl

一个测试页TemplatedControlWithContentPage.xaml

<Page
x:Class="SmallTests2018.TemplatedControlWithContentPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SmallTests2018"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<local:TemplatedControlWithContent>
<TextBlock>Hello World!</TextBlock>
</local:TemplatedControlWithContent>
</Page>

它在页面 XAML 设计器中的外观

enter image description here

关于c# - 模板控件中的 ContentPresenter 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53697165/

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