I've created a custom button with a ControlTemplate.
I used a ControlTemplate to make it possible to bind the default properties of UserControl, such as Background or Foreground.
But, if I add custom dependency properties (for example CornerRadius) I get two errors:
- "The member 'CornerRadius' is not recognized or is not accessible."
- "Cannot find the static member 'CornerRadiusProperty' on the type 'UserControl'."
Xaml:
<UserControl x:Class="MyProject.MyButton" 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="50" d:DesignWidth="50" BorderThickness="1" BorderBrush="White" Background="Black" Content="OK" Foreground="White"> <UserControl.Template> <ControlTemplate TargetType="UserControl"> <Border Name="ground" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" CornerRadius="{TemplateBinding CornerRadius}"> <Label Name="content" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" FontFamily="{TemplateBinding FontFamily}" FontWeight="{TemplateBinding FontWeight}" FontSize="{TemplateBinding FontSize}"/> </Border> </ControlTemplate> </UserControl.Template> </UserControl> Code behind:
namespace MyProject { public partial class MyButton : UserControl { public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(MyButton)); public CornerRadius CornerRadius { get => (CornerRadius)GetValue(CornerRadiusProperty); set => SetValue(CornerRadiusProperty, value); } public MyButton() => InitializeComponent(); } } If I use the solution specified here User control with custom properties I get this problem Wpf - Custom control: How to override default properties?.
So, there is a solution that avoid both problems?
TargetTypeofControlTemplateis incorrect. It should be MyButton.ArgumentException: 'MyButton' ControlTemplate TargetType does not match templated type 'UserControl'.seems only a rendering problem of the editor. When I build my application and run it, it works correctly: user-images.githubusercontent.com/32025549/… Strange...