2013-12-10 3 views
1

Я знаю, как установить кнопку по умолчанию в виде квадратной серой кнопки, но как ее динамически изменить на круглую кнопку?WPF как установить кнопку круга

Я попытался установить в качестве кнопки по умолчанию, но он не отображает кнопку круг

пример:

Button btnb = new Button(); 
btnb.Name = "b" + a.Key.ToString(); 
btnb.MinHeight = 100; 
btnb.MinWidth = 100; 
+0

Зачем вам это нужно динамически устанавливать? –

+0

Вы используете XAML? – Tan

+3

http://stackoverflow.com/questions/12470412/how-to-implement-a-circle-button-in-xaml –

ответ

0

Вы должны изменить стиль кнопки динамически. Поместите отдельный файл ресурсов в стиле кнопки, и когда вам нужно назначить этот стиль динамически.

В вашем XAML файле определить стиль ..

<Window.Resources>  
<Style x:Key="RoundButtonStyleKey" TargetType="{x:Type Button}"> 
//Your Style goes here.. 
</Style> 
</Window.Resources> 

код за поиск стиля и назначить его ...

Button btnb = new Button(); 

btnb.Name = "b" + a.Key.ToString(); 
btnb.MinHeight = 100; 
btnb.MinWidth = 100; 
btnbStyle = (Style)(this.Resources["RoundButtonStyleKey"]); 
+0

theres ошибка, приложите надлежащим образом window.resources не определено на сетке или один из его классов оснований – user3044300

+0

Вы добавили стиль в свои ресурсы окна? – Sampath

2

Вы можете определить ControlTemplate для вашего Button, но это гораздо проще делать в XAML, чем в C#. Создание один в коде гораздо сложнее:

ControlTemplate circleButtonTemplate = new ControlTemplate(typeof(Button)); 

// Create the circle 
FrameworkElementFactory circle = new FrameworkElementFactory(typeof(Ellipse)); 
circle.SetValue(Ellipse.FillProperty, Brushes.LightGreen); 
circle.SetValue(Ellipse.StrokeProperty, Brushes.Black); 
circle.SetValue(Ellipse.StrokeThicknessProperty, 1.0); 

// Create the ContentPresenter to show the Button.Content 
FrameworkElementFactory presenter = new FrameworkElementFactory(typeof(ContentPresenter)); 
presenter.SetValue(ContentPresenter.ContentProperty, new TemplateBindingExtension(Button.ContentProperty)); 
presenter.SetValue(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Center); 
presenter.SetValue(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Center); 

// Create the Grid to hold both of the elements 
FrameworkElementFactory grid = new FrameworkElementFactory(typeof(Grid)); 
grid.AppendChild(circle); 
grid.AppendChild(presenter); 

// Set the Grid as the ControlTemplate.VisualTree 
circleButtonTemplate.VisualTree = grid; 

// Set the ControlTemplate as the Button.Template 
CircleButton.Template = circleButtonTemplate; 

И XAML:

<Button Name="CircleButton" Content="Click Me" Width="150" Height="150" /> 
Смежные вопросы