0

Есть кнопка

<UserControl x:Class="WCL1.RoundButton"
             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" 
             xmlns:local="clr-namespace:WCL1"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Button Height="{Binding ElementName=RoundButton, Path=Height}" Width="{Binding ElementName=RoundButton, Path=Wight}" VerticalAlignment="Top" HorizontalAlignment="Left">
            <Button.Template>
                <ControlTemplate>
                    <Grid x:Name="controlLayout">
                        <Ellipse x:Name="buttonSurface" Fill="LightBlue"></Ellipse>
                        <Label x:Name="buttonCaption" VerticalAlignment="Center"
                               HorizontalAlignment="Center"
                               FontSize="20" Content="{Binding ElementName=RoundButton, Path=Text}"></Label>
                    </Grid>
                </ControlTemplate>
            </Button.Template>
        </Button>
    </Grid>
</UserControl>

public partial class RoundButton : UserControl
    {
        static DependencyProperty TextProperty;
        static DependencyProperty FillProperty;
       // static DependencyProperty HeightProperty;
        //static DependencyProperty FontSizeProperty;
        //static DependencyProperty FillProperty;
        //static DependencyProperty FillProperty;
        //static DependencyProperty FillProperty;
        //static DependencyProperty FillProperty;
        public RoundButton()
        {
            TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(RoundButton),null);
            FillProperty = DependencyProperty.Register("Fill", typeof(string), typeof(RoundButton), null);
            InitializeComponent();
        }
        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }
        public Brush Fill
        {
            get { return (Brush)GetValue(FillProperty); }
            set { SetValue(FillProperty, value); }
        }
        private static void OnContentChanged(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            RoundButton rb = (RoundButton)sender;
        }
     }

Подключаю библиотеку к проекту и хочу использовать эту кнопку

<myDll:RoundButton Height="30" Width="30"></myDll:RoundButton>

Но на все свойства ноль реакции, а на значение Fill вообще говорит, что оно не допустимо,а text "свойство text уже зарегистрировано в RoundButton" и выдает ошибку.

Как сделать этот UserControl максимально похожим на обычный элемент Button?

P.S.

Было решено отказаться от UserControl, а использовать настраиваемую библиотеку элементов управления

namespace WCCL1
{
    /// <summary>
    /// Выполните шаги 1a или 1b, а затем 2, чтобы использовать этот пользовательский элемент управления в файле XAML.
    ///
    /// Шаг 1a. Использование пользовательского элемента управления в файле XAML, существующем в текущем проекте.
    /// Добавьте атрибут XmlNamespace в корневой элемент файла разметки, где он 
    /// будет использоваться:
    ///
    ///     xmlns:MyNamespace="clr-namespace:WCCL1"
    ///
    ///
    /// Шаг 1б. Использование пользовательского элемента управления в файле XAML, существующем в другом проекте.
    /// Добавьте атрибут XmlNamespace в корневой элемент файла разметки, где он 
    /// будет использоваться:
    ///
    ///     xmlns:MyNamespace="clr-namespace:WCCL1;assembly=WCCL1"
    ///
    /// Потребуется также добавить ссылку из проекта, в котором находится файл XAML,
    /// на данный проект и пересобрать во избежание ошибок компиляции:
    ///
    ///     Щелкните правой кнопкой мыши нужный проект в обозревателе решений и выберите
    ///     "Добавить ссылку"->"Проекты"->[Поиск и выбор проекта]
    ///
    ///
    /// Шаг 2)
    /// Теперь можно использовать элемент управления в файле XAML.
    ///
    ///     <MyNamespace:RoundButton/>
    ///
    /// </summary>
    public class RoundButton : Control
    {
        string dText = "RounButton";
        Brush dFill = Brushes.Blue;
        public string Text
        {
            get { return dText; }
            set { dText = value; }
        }
        public Brush Fill
        {
            get { return dFill; }
            set { dFill = value; }
        }
        static RoundButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(RoundButton), new FrameworkPropertyMetadata(typeof(RoundButton)));
        }
    }
}

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WCCL1">


    <Style TargetType="{x:Type local:RoundButton}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:RoundButton}">
                    <Grid x:Name="controlLayout">
                        <Ellipse x:Name="buttonSurface" Fill="{Binding Fill}"></Ellipse>
                        <Label x:Name="buttonCaption" VerticalAlignment="Center"
                               HorizontalAlignment="Center"
                               FontWeight="Bold" FontSize="20" Content="{Binding Text}"></Label>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Как теперь подключить эту библиотеку и правильно ли я все забиндил?

1 ответ 1

2

Судя по всему, вам не нужен не UserControl, а обыкновенный стиль с переопределением Template'а.

<Style TargetType="Button" x:Key="RoundButtonStyle">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid x:Name="controlLayout">
                    <Ellipse x:Name="buttonSurface" Fill="LightBlue"/>
                    <ContentPresenter
                        TextBlock.FontSize="20" Content="{TemplateBinding Content}"
                        HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Применять так:

<Button Style="{StaticResource RoundButtonStyle}">
    Test
</Button>

Ошибка в вашем коде — вы используете ElementName=RoundButton, но не определяете элемент с таким именем. Кроме того, вы должны вызывать DependencyProperty.Register в статическом конструкторе, иначе получите ошибку, когда попробуете использовать контрол во второй раз.


В новом коде ошибки:

  1. Вы в RoundButton определяете не DependencyProperty, а обыкновенные свойства. Это неправильно.
  2. Вместо {Binding Fill} нужно {TemplateBinding Fill}, и то же для Text. В остальном должно работать, по идее.

Но если ваша цель всё же быть похожим на нормальную кнопку, лучше попробовать просто поменять стиль (если можно, даже не менять Template).

7
  • Я решил использовать не UserControl, a сделать библиотеку Custom Control Library. Но все равно не понимаю, как все настроить и подключить ее.
    – Alex
    29 мая 2016 в 15:45
  • И где Вы определили элемент с именем?
    – Alex
    29 мая 2016 в 15:53
  • @SanychGoilo: Обновил ответ. // Объявлять элемент с именем не обязательно, можно вместо этого использовать TemplateBinding.
    – VladD
    29 мая 2016 в 16:01
  • Как потом подключить dll в xaml?
    – Alex
    29 мая 2016 в 16:03
  • @SanychGoilo: В каком смысле «подключить DLL»? Вы имеете в виду xmlns:lib="clr-namespace:WCCL1;assembly=WCCL1"?
    – VladD
    29 мая 2016 в 16:38

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.