2013-12-10 77 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" />