Связывание пользовательского свойства зависимости на пользовательском элементе управления с помощью ControlTemplate - PullRequest
0 голосов
/ 24 января 2019

Я создал пользовательскую кнопку с ControlTemplate.
. Я использовал ControlTemplate, чтобы сделать возможной привязку свойств по умолчанию UserControl, таких как Background или Foreground.

Но, если я добавлю пользовательские свойства зависимостей (например, CornerRadius), я получу две ошибки:

  1. "Элемент 'CornerRadius' не распознан или не распознандоступный. "
  2. " Не удается найти статический член 'CornerRadiusProperty' для типа '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>

Код:

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();
    }
}

Если я использую решение, указанное здесь Пользовательский элемент управления с пользовательскими свойствами Я получаю этоПроблема Wpf - Пользовательский элемент управления: Как переопределить свойства по умолчанию? .

Итак, есть решение, позволяющее избежать обеих проблем?

1 Ответ

0 голосов
/ 24 января 2019

Пользовательская кнопка не должна быть UserControl, а вместо этого напрямую наследоваться от кнопки.

Добавьте «Пользовательский элемент управления (WPF)» в проект Visual Studio и измените его следующим образом:

public class MyButton : Button
{
    static MyButton()
    {
        DefaultStyleKeyProperty.OverrideMetadata(
            typeof(MyButton),
            new FrameworkPropertyMetadata(typeof(MyButton)));
    }

    public static readonly DependencyProperty CornerRadiusProperty =
        DependencyProperty.Register(
            nameof(CornerRadius), typeof(CornerRadius), typeof(MyButton));

    public CornerRadius CornerRadius
    {
        get => (CornerRadius)GetValue(CornerRadiusProperty);
        set => SetValue(CornerRadiusProperty, value);
    }
}

Затем измените стиль по умолчанию в сгенерированном файле Themes\Generic.xaml:

<Style TargetType="local:MyButton">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyButton">
                <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>
        </Setter.Value>
    </Setter>
</Style>

Подробнее см. Обзор авторизации управления .

...