Click here to Skip to main content
12,831,626 members (31,551 online)
Click here to Skip to main content
Add your own
alternative version


38 bookmarked
Posted 8 Jun 2009

Dynamic Button Control (C# code or XAML code)

, 8 Jun 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
Dynamic Button Control (C# code or XAML code)


This is a simple button control which is created by XAML and C# code. These techniques are used by two languages, either XAML or C# . In both cases, the functionality is the same but the declaration is different. The following functionalities are used to create a control.

1. ResourceDictionary

ResourceDictionary class is typically an implicit collection element that is the object element value of several Resources properties.

2. Style

A style is most commonly declared as a resource inside the Resources section. Because styles are resources, they obey the same scoping rules that apply to all resources, so where you declare a style affects where it can be applied. If, for instance, you declare the style in the root element of your application definition XAML file, the style can be used anywhere in your application. If you are creating a navigation application and declare the style in one of the application's XAML files, the style can be used only in that XAML file.

3. ControlTemplate

The ControlTemplate allows you to specify the visual structure of a control. The control author can define the default ControlTemplate and the application author can override the ControlTemplate to reconstruct the visual structure of the control.

4. Triggers

WPF defines properties that correspond to end-user actions, such as the IsMouseOver property that is set to true when the user hovers the cursor over a UIElement or the corresponding IsMouseOver property of a ContentElement. Representing end-user actions in property values, along with the Trigger element, allows WPF styles to change property values based on those end-user actions, all from within markup.

5. GradientBrush

A LinearGradientBrush paints an area with a linear gradient. A linear gradient defines a gradient along a line. The line's end points are defined by the StartPoint and EndPoint properties of the linear gradient. A LinearGradientBrush brush paints its GradientStops along this line. The default linear gradient is diagonal. In the default, the StartPoint of a linear gradient is (0,0), the upper-left corner of the area being painted, and its EndPoint is (1,1), the lower-right corner of the area being painted. The colors in the resulting gradient are interpolated along the diagonal path.

6. FrameworkElementFactory

Supports the creation of templates.

C# Source Code

this.Content = "C#Code";


LinearGradientBrush gradient_GlassBackgroundFill = new LinearGradientBrush();
gradient_GlassBackgroundFill.StartPoint = new Point(0, 0);
gradient_GlassBackgroundFill.EndPoint = new Point(0, 1);

GradientStop color_BackgroundFill = new GradientStop();
color_BackgroundFill.Offset = 0;
color_BackgroundFill.Color = (Color)ColorConverter.ConvertFromString("#ff4b58");

GradientStop color2_BackgroundFill = new GradientStop();
color2_BackgroundFill.Offset = 1;
color2_BackgroundFill.Color = (Color)ColorConverter.ConvertFromString("#a91e28");



RadialGradientBrush gradient_HoverGlassBackgroundFill = new RadialGradientBrush();
gradient_HoverGlassBackgroundFill.Center = new Point(0.5, 0.5);

GradientStop color_HoverGlassBackgroundFill = new GradientStop();
color_HoverGlassBackgroundFill.Offset = 0;
color_HoverGlassBackgroundFill.Color = 

GradientStop color2_HoverGlassBackgroundFill = new GradientStop();
color2_HoverGlassBackgroundFill.Offset = 1;
color2_HoverGlassBackgroundFill.Color = 



LinearGradientBrush highlightFill = new LinearGradientBrush();
highlightFill.StartPoint = new Point(0, 0);
highlightFill.EndPoint = new Point(0, 1);

GradientStop color_highlightFill = new GradientStop();
color_highlightFill.Offset = 0;
color_highlightFill.Color = (Color)ColorConverter.ConvertFromString("#FFFFFFFF");

GradientStop color2_highlightFill = new GradientStop();
color2_highlightFill.Offset = 1;
color2_highlightFill.Color = (Color)ColorConverter.ConvertFromString("#00000000");


LinearGradientBrush borderStroke = new LinearGradientBrush();
borderStroke.StartPoint = new Point(0, 0);
borderStroke.EndPoint = new Point(0, 1);

GradientStop color_borderStroke = new GradientStop();
color_borderStroke.Offset = 0;
color_borderStroke.Color = (Color)ColorConverter.ConvertFromString("#c7c7c7");

GradientStop color2_borderStroke = new GradientStop();
color2_borderStroke.Offset = 1;
color2_borderStroke.Color = (Color)ColorConverter.ConvertFromString("#b0b0b0");



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

FrameworkElementFactory grid = new FrameworkElementFactory(typeof(Grid));
grid.SetValue(Grid.RenderTransformOriginProperty, new Point(0.5, 0.5));


FrameworkElementFactory ele_BorderStock = new FrameworkElementFactory(typeof(Border));
ele_BorderStock.Name = "Outline";
ele_BorderStock.SetValue(Border.CornerRadiusProperty, new CornerRadius(9.0));
ele_BorderStock.SetValue(Border.BackgroundProperty, Brushes.Red);
ele_BorderStock.SetValue(Border.BorderBrushProperty, borderStroke);
ele_BorderStock.SetValue(Border.BorderThicknessProperty, new Thickness(1));

FrameworkElementFactory ele_GlassBackground = 
		new FrameworkElementFactory(typeof(Rectangle));
ele_GlassBackground.Name = "GlassBackground";
ele_GlassBackground.SetValue(Rectangle.MarginProperty, new Thickness(1, 1, 2, 2));
ele_GlassBackground.SetValue(Rectangle.RadiusXProperty, 9.0);
ele_GlassBackground.SetValue(Rectangle.RadiusYProperty, 9.0);
ele_GlassBackground.SetValue(Rectangle.FillProperty, gradient_GlassBackgroundFill);

FrameworkElementFactory ele_Highlight = new FrameworkElementFactory(typeof(Rectangle));
ele_Highlight.SetValue(Rectangle.MarginProperty, new Thickness(1, 1, 2, 2));
ele_Highlight.SetValue(Rectangle.RadiusXProperty, 9.0);
ele_Highlight.SetValue(Rectangle.RadiusYProperty, 9.0);
ele_Highlight.SetValue(Rectangle.OpacityProperty, 1.0);
ele_Highlight.SetValue(Rectangle.FillProperty, highlightFill);

FrameworkElementFactory ContentPresenterAll =
	new FrameworkElementFactory(typeof(ContentPresenter));
	(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Center);
	(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Center);



Trigger tg_IsMouseOver = new Trigger();
tg_IsMouseOver.Property = IsMouseOverProperty;
tg_IsMouseOver.Value = true;

Setter str_IsMouseOver = new Setter();
str_IsMouseOver.TargetName = "GlassBackground";
str_IsMouseOver.Property = Rectangle.FillProperty;
str_IsMouseOver.Value = gradient_HoverGlassBackgroundFill;



Trigger tg_IsPressed = new Trigger();
tg_IsPressed.Property = Button.IsPressedProperty;
tg_IsPressed.Value = true;

Setter str_IsPressed = new Setter();
str_IsPressed.TargetName = "GlassBackground";
str_IsPressed.Property = Rectangle.FillProperty;
str_IsPressed.Value = Brushes.Red;


template.VisualTree = grid;

Style newStyle = new Style();
newStyle.TargetType = typeof(Button);

Setter str_margin = new Setter(Button.MarginProperty, new Thickness(1.0));
Setter str_snapsToDevicePixes = new Setter(Button.SnapsToDevicePixelsProperty, true);
Setter str_OverridesDefaultStyle = 
	new Setter(Button.OverridesDefaultStyleProperty, true);
Setter str_minHeight = new Setter(Button.MinHeightProperty, 16.0);
Setter str_minWidth = new Setter(Button.MinWidthProperty, 16.0);
Setter str_fontFamiy = new Setter(Button.FontFamilyProperty, new FontFamily("Verdana"));
FontSizeConverter myFontSizeConverter = new FontSizeConverter();
Setter str_fontSize = new Setter
    (Button.FontSizeProperty, (Double)myFontSizeConverter.ConvertFromString("11px"));
Setter str_foreground = new Setter(Button.ForegroundProperty, Brushes.White);
Setter str_ModifiedTemplate = new Setter(TemplateProperty, template);


this.Style = newStyle;

XAML Source Code

<Style x:Key="GlassButton" TargetType="{x:Type Button}">
   <Setter Property="Margin" Value="1" />
   <Setter Property="SnapsToDevicePixels" Value="true"> </Setter>
   <Setter Property="OverridesDefaultStyle" Value="true"> </Setter>
   <Setter Property="MinHeight" Value="16"> </Setter>
   <Setter Property="MinWidth" Value="16"> </Setter>
   <Setter Property="FontFamily" Value="Verdana"> </Setter>
   <Setter Property="FontSize" Value="11px" />
   <Setter Property="Foreground" Value="White" />
   <Setter Property="Template">
       <ControlTemplate TargetType="Button" >
           <Grid x:Name="Content" RenderTransformOrigin="0.5,0.5">
           <Border Name="Outline" CornerRadius="9"
           Background="{StaticResource ButtonPushedFill}"
              BorderBrush="{StaticResource BorderStroke}"
              BorderThickness="1" />
             <!--<span class="code-comment"> Background --></span>
           <Rectangle x:Name="GlassBackground"
           Margin="1,1,2,2" RadiusX="9" RadiusY="9"
            Fill="{StaticResource GlassBackgroundFill}">
           <Rectangle x:Name="Highlight" Margin="1,1,2,2" RadiusX="9"
            RadiusY="9" Opacity="1" Fill="{StaticResource HighlightFill}">
           <!--<span class="code-comment"> This aligns the text in the center of the button --></span>
           <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" />

           <!--<span class="code-comment"> Triggers --></span>
              <Trigger Property="IsMouseOver" Value="true">
                 <Setter TargetName="GlassBackground"
       Property="Fill" Value="{StaticResource HoverGlassBackgroundFill}" />
              <Trigger Property="IsPressed" Value="true">
                 <Setter TargetName="GlassBackground"
       Property="Fill" Value="{StaticResource ButtonPushedFill}" />



About the Author

I started my IT career in 2003 with C++ and VC++, I gained good experience in the IT industry. Finally I moved to .NET Technologies and I am involved in many .NET projects. I have good experience in packaging and deployment of .NET projects. I have worked on Graphics and digital imaging process, and developed an algorithm for high speed printing in graphics mode, this was one great success in that project. I have developed custom controls in C#. I also have good knowledge of latest technologies like WPF and WCF, good learning skills and interest to work on advanced technologies. Currently I am working for Wipro Technologies. My hobbies include reading books, swimming, and listening to music.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Jeeva Jose
Software Developer (Senior)
India India
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy Vote of 4 Pin
David Roh8-Feb-10 6:40
memberDavid Roh8-Feb-10 6:40 
It's true that the article should have more explanation; however, the code clearly shows how to create a dynamic button in code - this information can be difficult to find and put together, so while I can't give a five, I can give a four.

David Roh
General[My vote of 1] Not Enough Descriptive Text Pin
John Simmons / outlaw programmer9-Jun-09 1:01
mvpJohn Simmons / outlaw programmer9-Jun-09 1:01 
GeneralXAML vs C# Pin
Dewey8-Jun-09 22:36
memberDewey8-Jun-09 22:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170326.1 | Last Updated 8 Jun 2009
Article Copyright 2009 by Jeeva Jose
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid