我创建了一个模板控件 . 我所做的所有默认样式都是添加内容演示者 . 我还引用了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>
我应该怎么做才能使用内容演示者?
如果我尝试使用用户控件,相同的方法可以正常工作 .
2 回答
虽然答案是由@DK发布的 . 很完美,我试图使用Control而不是ContentControl . 原因是因为我只是在努力熟悉UWP .
他的回答非常有助于我解决继承自Control的控件的问题 .
TestingControl.cs
Style
Usage
要在自定义模板化控件中处理XAML内容,您必须从ContentControl派生控件或保持继承自Control,实现自定义ContentProperty并将ContentPresenter绑定到它 .
使用
ContentControl
会更容易一些,这里's the code you'可能最终会结束 .Themes / Generic.xaml中的样式定义
我更喜欢将
Border
绑定到模板化控件属性,因此使用它的开发人员可以更好地控制外观 .这里的椭圆是一些额外自定义内容的示例 .
TemplatedControlWithContent.cs
ContentControl
.测试页面TemplatedControlWithContentPage.xaml
它在页面XAML设计器中的外观