Reputation: 9403
I'd like to be able to do something like this:
.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>
But it doesn't work. Not-so-surprisingly, when you start an element name with UserControl
, the compiler only looks for properties defined on UserControl
itself. But changing the element name to <MyControl.MyTemplate>
(with the proper namespace prefix) doesn't work either; the compiler tries to interpret MyTemplate
as an attached property in this case.
Is there any way to achieve this aside from defining the value in a resource and then assigning it to the property from codebehind?
Upvotes: 2
Views: 32
Reputation: 128145
You can set the property by a Style:
<UserControl ...>
<UserControl.Style>
<Style>
<Setter Property="local:MyControl.MyTemplate">
<Setter.Value>
<DataTemplate />
</Setter.Value>
</Setter>
</Style>
</UserControl.Style>
...
</UserControl>
Upvotes: 2