Как сделать круглые кнопки c wpf
Перейти к содержимому

Как сделать круглые кнопки c wpf

  • автор:

 

Circular WPF Button Template

Here’s another WPF button template, since my first one continues to be one of the most popular posts on my blog. This one is in response to a question about how the button could be made circular. The basic background of the button is formed by superimposing three circles on top of each other:

Here’s what that looks like:

Now to turn it into a template, we follow a very similar process to before. We allow the Background colour to be overriden by the user if required. I couldn’t come up with a neat way of forcing the button to be circular, but it is not too much of a chore to set the Height and Width in XAML.

The focus rectangle has been made circular. For the IsPressed effect, I simply change the angle of the linear gradient of the inner circle a little, and move the ContentPresenter down a bit, which seems to work OK. I haven’t created any triggers yet for IsMouseOver, IsEnabled or IsFocused, mainly because I’m not quite sure what would create a the right visual effect.

Here’s how we declare a few of these buttons of different sizes, and with different background colours:

Sadly, the use of ControlTemplate triggers means that this template can’t be used directly in Silverlight. I’ll maybe look into converting them to VisualStates for a future blog post.

Comments

Comment by Anonymous

Please continue to put out this kind of stuff on your blog!

Anonymous

Comment by Anonymous

Why can't i move the Buttons around? o.O

Anonymous

Comment by Kevin Marois

How do I copy the code off your blog without getting all the line numbers?

Comment by Kevin Marois

How do I copy the code off your blog without the line numbers?

Comment by Mark H

@Kevin — double-click in the code area — it will select the text without the line numbers.

Comment by Anonymous

how to wrap the button text

Anonymous

Comment by Anonymous

Hi, I am getting this message:
The attached property 'Page.Resources' is not defined on or one of its base classes.

Can you help me, please?

Anonymous

Comment by Phil Ruse

Having switched to WPF end of last year, on the one hand it's scary how much I have to learn (though that's what makes it fun too), on the other I am continually grateful for contributions to 'the community' (if that doesn't sound too pompous?!) such as this. Much obliged 🙂

Как я делал user-control на WPF (VS2019, c#)

Исходная ситуация: в рамках проекта по разработке декстопного приложения под винду заказчиком было выражено фи по поводу деталей интерфейса, в частности кнопок. Возникла необходимость сделать свой контрол а-ля навигационные кнопки в браузерах.

Задача: сделать контрол кнопки (WPF): круглая, с возможностью использования в качестве иконки объекта Path, с возможностью использовать свойство IsChecked, и сменой цветовых схем при наведении/нажатии.

В итоге кнопка будет иметь следующий внешний вид (иконки само-собой произвольные):

 

Переходим к реализации. Назовем наш контрол VectorRoundButton, наследуя его от UserControl. XAML разметка нашего контрола предельно проста: масштабируемый Grid; объект Ellipse, символизирующий столь желанную круглую кнопку и объект Path с выбранной иконкой.

Для контроля внешнего вида и состояния кнопки будем использовать следующие свойства:

IsCheckable — возможность отображения в режиме чек-бокса
IsChecked — в речиме чек-бокса — включено/выключено (кнопка обводится кружком)
ActiveButtonColor — цвет активной кнопки (при наведенном курсоре)
InactiveButtonColor — цвет кнопки в нормальном состоянии
ButtonIcon — иконка кнопки

Для корректной работы контрола в процессе визуальной верстки нашего приложения необходимо реализовать привязку данных через соответствующие DependencyProperty:

В описанных присоединенных свойствах указаны обработчики событий на их изменение, связанные с выбором иконки, цвета, нажатием на кнопку и т.д. Ниже приводятся методы, реализующие данные обработчики.

Обработчик изменения иконки нашей кнопки:

Обработчики изменения цветов кнопки:

Обработчики изменения состояния включено/выключено для кнопки в режиме чек-бокс, а также включения/выключения данного режима:

Осталось совсем немного — реализовать реакцию кнопки на перемещение мышки через данный контрол, а также событие нажатия левой кнопки мыши:

В итоге, имеем следующий код пользовательского контрола:

Во собственно и все =) Понимаю, что все написанное до банального просто и вряд ли представляет интерес для серьезных разработчиков, тем более что реализация довольно кривая, но в рамках каких-либо учебных проектов может кому и сгодится.

Как сделать круглые кнопки c wpf

Gray Pipe

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

i don’t want to learn templates and don’t want my buttons to be glossary , i just want the corners of my simple button to be rounded.

thousands of examples , not one SIMPLE example of button with rounded corners anywhere.

Answers

I found the problem , the border should be outside the button tag — arounf it:

  • Marked as answer by Annabella Luo Tuesday, January 3, 2012 5:13 PM

All replies

Harshad. Always 4 U

I found the problem , the border should be outside the button tag — arounf it:

  • Marked as answer by Annabella Luo Tuesday, January 3, 2012 5:13 PM

-Thanks and Regards Dileep Kumar

Note that when you set the controltemplate for a control, you entirely replace the default template.

I mention this because the standar button template has triggers for mouseover, ispressed and IsEnabled.

It’s therefore often preferable to edit a copy of the standard template.

This is almost trivial, so you don’t need to learn all about templates to do it.

Just know that you can get the template by clicking the square next to the Template property of any button.

You then make a very simple change to that template and your button has rounded corners

Create Buttons With Rounded Corner In WPF

In this post, we’ll learn to create buttons with rounded corners in WPF.

The default button template in WPF has a border. So, we have to change value of the CornerRadius property of the border in the button template.

Single Button With Rounded Corners

If you want rounded corners for a single button, modify the XAML code as shown below.

Apply to all Buttons

To apply rounded corners to all buttons in the application, add this style in the App.xaml file in the Application.Resources tag.

Here is a screenshot of the result.

report this ad

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *