2013-12-10 76 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

您可以为您Button定义ControlTemplate,但它是如此简单得多在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" />