【发布时间】:2019-05-09 12:50:00
【问题描述】:
我希望能够做这样的事情:
.xaml.cs:
public partial class MyControl : UserControl
{
public MyControl() => InitializeComponent();
public static readonly DependencyProperty MyTemplateProperty = DependencyProperty.Register(
"MyTemplate", typeof(DataTemplate), typeof(MyControl), new PropertyMetadata(default(DataTemplate)));
public DataTemplate MyTemplate
{
get => (DataTemplate) GetValue(MyTemplateProperty);
set => SetValue(MyTemplateProperty, value);
}
}
.xaml:
<UserControl x:Class="MyControl"> <!-- etc. -->
<Grid />
<!-- does not compile-->
<UserControl.MyTemplate>
<DataTemplate />
</UserControl.MyTemplate>
</UserControl>
但它不起作用。毫不奇怪,当您以 UserControl 开头元素名称时,编译器仅查找在 UserControl 本身上定义的属性。但是将元素名称更改为<MyControl.MyTemplate>(带有正确的命名空间前缀)也不起作用;在这种情况下,编译器会尝试将 MyTemplate 解释为附加属性。
除了在资源中定义值然后从代码隐藏中将其分配给属性之外,还有什么方法可以实现这一点?
【问题讨论】:
标签: wpf xaml user-controls