Monday, September 20, 2010

WPF - Resource Dictionary in WPF

In a ResouceDictionary we can keep our custom styles, DataTemplates, ControlTemplates, even Custom Definitions of Brush,Color, Background and lot of other stuff. But the important thing is that we have to assign a key to each of them since its a Dictionary. we can also give name to the styles.In short you can create your own theme for appliation.

Step 1
Create a WPF application.

Step 2
Add a ResourceDictionary file in project,go to the solution explorer,right click on project,select Add and click on New Item then select Resource Dictionary(WPF) and give the name as MyDictionary.xaml then click Add,it is look like this



















Click on image for better view

Step 3
In ResourceDictionary file write a XAML code for apply style for button control.it is look like this



<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    
    <Style x:Key="BtnStyle" TargetType="Button">
        
        <Setter Property="Background" Value="Orange"></Setter>
        <Setter Property="Foreground" Value="Gray"></Setter>
        
    </Style>
</ResourceDictionary>

Step 4
Now we can initialise the path of Resource Dictionary in Window.Resources element in MainWindow.xaml ,it is look like this
  
 <Window.Resources>
       
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="MyDictionary.xaml"></ResourceDictionary> 
            </ResourceDictionary.MergedDictionaries>  
        </ResourceDictionary>
        
    </Window.Resources>

Step 5
Add a button control on window and then apply style on button control,it is look like this

 <Grid>
        <Button Content="OK" Height="23" HorizontalAlignment="Left" Margin="145,112,0,0" Name="btnOK" VerticalAlignment="Top" Width="75" Style="{StaticResource BtnStyle}" />
        </Grid>

Full XAML Code

<Window x:Class="WpfResourceDictionary.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="400" Background="gray">
    <Window.Resources>
       
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="MyDictionary.xaml"></ResourceDictionary> 
            </ResourceDictionary.MergedDictionaries>  
        </ResourceDictionary>
        
    </Window.Resources>
        <Grid>
        <Button Content="OK" Height="23" HorizontalAlignment="Left" Margin="145,112,0,0" Name="btnOK" VerticalAlignment="Top" Width="75" Style="{StaticResource BtnStyle}" />
        </Grid>
</Window>

Run the project

Download
Download Source Code

日本の開発者のための。
私は日本で働くことは興味深いです
誰もが開発者として募集したい場合は私に知らせてください
スキル - WPF,Silverlight and Window Phone 7

Sunday, September 19, 2010

LINQ - Linq to Object Part 6 Join

Linq to Object Part 5

Joins are the most important function of SQL Operators. Linq supports join operations using the join operator. The join operator performs an inner join of two collections based on matching keys extracted from the elements.

Let See how to create a Join.

Step 1
Create a web application and give the solution name as SolLinqJoin.

Step 2
Add a gridview in page,it is look like this


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GvStudent" runat="server" BackColor="White" 
            BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" 
            EnableModelValidation="True" ForeColor="Black" GridLines="Vertical">
            <AlternatingRowStyle BackColor="#CCCCCC" />
            <FooterStyle BackColor="#CCCCCC" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
        </asp:GridView>  
    </div>
    </form>
</body>
</html>

Step 3
Create a Division class in App_Code folder,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
///  Add the Division Data
/// </summary>
public class Division
{
    #region Property

    public int DivID
    {
        get;
        set;
    }
    public String DivName
    {
        get;
        set;
    }

    #endregion
}

Step 4
Create a Student class in App_Code folder,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Add a Student Data
/// </summary>
public class Student
{
    #region Property

    public int StudentID
    {
        get;
        set;
    }

    public String Name
    {
        get;
        set;
    }

    public int DivID
    {
        get;
        set;
    }


    #endregion
}

Step 5
Create a method for add division and student data in default.cs class,it is look like this

 /// <summary>
    /// Add the Division Data
    /// </summary>
    /// <returns>List</returns>
    private List<Division> AddDivisionData()
    {
        try
        {
            Division Div1 = new Division();
            Div1.DivID = 1;
            Div1.DivName = "A";

            Division Div2 = new Division();
            Div2.DivID = 2;
            Div2.DivName = "B";

            Division Div3 = new Division();
            Div3.DivID=3;
            Div3.DivName="C";

            List<Division> ListDiv = new List<Division>();
            ListDiv.Add(Div1);
            ListDiv.Add(Div2);
            ListDiv.Add(Div3);

            return ListDiv; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    /// <summary>
    /// Add the Student Data
    /// </summary>
    /// <returns>List</returns>
    private List<Student> AddStudentData()
    {
        try
        {
            Student Std1 = new Student();
            Std1.StudentID = 1;  
            Std1.Name = "Kishor";
            Std1.DivID = 1;

            Student Std2 = new Student();
            Std2.StudentID = 2;  
            Std2.Name = "Kakashi";
            Std2.DivID = 1;  

            Student Std3 = new Student();
            Std3.StudentID = 3;  
            Std3.Name = "Lee";
            Std3.DivID  = 2;

            Student Std4 = new Student();
            Std4.StudentID = 4;
            Std4.Name = "Ramdas";
            Std4.DivID = 1;

            Student Std5 = new Student();
            Std5.StudentID = 5;
            Std5.Name = "Jhon";
            Std5.DivID = 2;

            Student Std6 = new Student();
            Std6.StudentID = 6;
            Std6.Name = "Jiraiya";
            Std6.DivID = 3;
           

            Student Std7 = new Student();
            Std7.StudentID = 7;
            Std7.Name = "shikamaro";
            Std7.DivID = 3;

            Student Std8 = new Student();
            Std8.StudentID = 8;
            Std8.Name = "Eun-ju";
            Std8.DivID = 1;

            Student Std9 = new Student();
            Std9.StudentID = 9;
            Std9.Name = "Naruto";
            Std9.DivID = 3;

            Student Std10 = new Student();
            Std10.StudentID = 10;
            Std10.Name = "David";
            Std10.DivID = 2;

            Student Std11 = new Student();
            Std11.StudentID = 11;
            Std11.Name = "Sakura";
            Std11.DivID = 2;
            

            List<Student> StudentObj = new List<Student>();
            StudentObj.Add(Std1);
            StudentObj.Add(Std2);
            StudentObj.Add(Std3);
            StudentObj.Add(Std4);
            StudentObj.Add(Std5);
            StudentObj.Add(Std6);
            StudentObj.Add(Std7);
            StudentObj.Add(Std8);
            StudentObj.Add(Std9);
            StudentObj.Add(Std10);
            StudentObj.Add(Std11);
           

            return StudentObj; 

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

Step 6
Perform join operation,it is look like this


  /// <summary>
    /// Perform join operation and display data in gridview
    /// </summary>
    /// <param name="ListDiv"></param>
    /// <param name="ListStudent"></param>
    private void Join(List<Division>ListDiv,List<Student>ListStudent)
    {
        try
        {
            /// get Division Data
            var DivQuery = from D in ListDiv
                           select D;

            /// Get Student Data
            var StudentQuery = from S in ListStudent
                               select S;

            /// Join Process

            var JoinQuery = from D in DivQuery
                                    join
                                        S in StudentQuery
                                    on
                                        D.DivID equals S.DivID
                                        orderby S.StudentID ascending 
                                    select new
                                    {
                                        StudentID=S.StudentID,
                                        Name=S.Name,
                                        Division=D.DivName 
                                    };

            /// Bind the Data in GridView
            GvStudent.DataSource = JoinQuery;
            GvStudent.DataBind();  
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }

Step 7
Call a Join method in Page_Load event, it is look like this

 protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                Join(AddDivisionData(), AddStudentData());   
            }
        }
        catch (Exception)
        { }
    }

Full .aspx.cs Code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                Join(AddDivisionData(), AddStudentData());   
            }
        }
        catch (Exception)
        { }
    }

    #region Methods
    /// <summary>
    /// Add the Division Data
    /// </summary>
    /// <returns>List</returns>
    private List<Division> AddDivisionData()
    {
        try
        {
            Division Div1 = new Division();
            Div1.DivID = 1;
            Div1.DivName = "A";

            Division Div2 = new Division();
            Div2.DivID = 2;
            Div2.DivName = "B";

            Division Div3 = new Division();
            Div3.DivID=3;
            Div3.DivName="C";

            List<Division> ListDiv = new List<Division>();
            ListDiv.Add(Div1);
            ListDiv.Add(Div2);
            ListDiv.Add(Div3);

            return ListDiv; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    /// <summary>
    /// Add the Student Data
    /// </summary>
    /// <returns>List</returns>
    private List<Student> AddStudentData()
    {
        try
        {
            Student Std1 = new Student();
            Std1.StudentID = 1;  
            Std1.Name = "Kishor";
            Std1.DivID = 1;

            Student Std2 = new Student();
            Std2.StudentID = 2;  
            Std2.Name = "Kakashi";
            Std2.DivID = 1;  

            Student Std3 = new Student();
            Std3.StudentID = 3;  
            Std3.Name = "Lee";
            Std3.DivID  = 2;

            Student Std4 = new Student();
            Std4.StudentID = 4;
            Std4.Name = "Ramdas";
            Std4.DivID = 1;

            Student Std5 = new Student();
            Std5.StudentID = 5;
            Std5.Name = "Jhon";
            Std5.DivID = 2;

            Student Std6 = new Student();
            Std6.StudentID = 6;
            Std6.Name = "Jiraiya";
            Std6.DivID = 3;
           

            Student Std7 = new Student();
            Std7.StudentID = 7;
            Std7.Name = "shikamaro";
            Std7.DivID = 3;

            Student Std8 = new Student();
            Std8.StudentID = 8;
            Std8.Name = "Eun-ju";
            Std8.DivID = 1;

            Student Std9 = new Student();
            Std9.StudentID = 9;
            Std9.Name = "Naruto";
            Std9.DivID = 3;

            Student Std10 = new Student();
            Std10.StudentID = 10;
            Std10.Name = "David";
            Std10.DivID = 2;

            Student Std11 = new Student();
            Std11.StudentID = 11;
            Std11.Name = "Sakura";
            Std11.DivID = 2;
            

            List<Student> StudentObj = new List<Student>();
            StudentObj.Add(Std1);
            StudentObj.Add(Std2);
            StudentObj.Add(Std3);
            StudentObj.Add(Std4);
            StudentObj.Add(Std5);
            StudentObj.Add(Std6);
            StudentObj.Add(Std7);
            StudentObj.Add(Std8);
            StudentObj.Add(Std9);
            StudentObj.Add(Std10);
            StudentObj.Add(Std11);
           

            return StudentObj; 

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    /// <summary>
    /// Perform join operation and display data in gridview
    /// </summary>
    /// <param name="ListDiv"></param>
    /// <param name="ListStudent"></param>
    private void Join(List<Division>ListDiv,List<Student>ListStudent)
    {
        try
        {
            /// get Division Data
            var DivQuery = from D in ListDiv
                           select D;

            /// Get Student Data
            var StudentQuery = from S in ListStudent
                               select S;

            /// Join Process

            var JoinQuery = from D in DivQuery
                                    join
                                        S in StudentQuery
                                    on
                                        D.DivID equals S.DivID
                                        orderby S.StudentID ascending 
                                    select new
                                    {
                                        StudentID=S.StudentID,
                                        Name=S.Name,
                                        Division=D.DivName 
                                    };

            /// Bind the Data in GridView
            GvStudent.DataSource = JoinQuery;
            GvStudent.DataBind();  
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }

    #endregion
}

Run the project.

Download
Download Source Code

LINQ - Linq to Object Part 5 Aggregate Operators

Linq to Object Part 4

Step 1
Create a web project.

Step 2
Create a AggregateOperators static class in App_Code folder,it is look like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Demo of Linq Aggregator Operators
/// </summary>
public static class AggregateOperators
{

    #region Methods

    /// <summary>
    /// Count the number of array
    /// </summary>
    /// <returns>int</returns>
    public static int CountData()
    {
        try
        {
            int[] Number = { 2, 5, 3, 7, 8 };

            var Query = (from Q in Number
                         select Q).Count<int>() ;

            return Query; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    /// <summary>
    /// Sum of the number of array
    /// </summary>
    /// <returns>int</returns>
    public static int SumData()
    {
        try
        {
            int[] Number = { 3, 5, 2, 10, 4, 6, 9 };

            var Query = (from Q in Number
                         select Q).Sum();

            return Query; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #endregion

    /// <summary>
    /// get the minimum number of array
    /// </summary>
    /// <returns>int</returns>
    public static int MinData()
    {
        try
        {
            int[] Number = { 4,7,3,8,6,2,6,1,5};

            var Query = (from Q in Number
                         select Q).Min();

            return Query; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);   
        }
    }

    /// <summary>
    /// get the maximum number of array
    /// </summary>
    /// <returns>int</returns>
    public static int MaxData()
    {
        try
        {
            int[] Number = { 4, 7, 3, 8, 6, 2, 6, 1, 5 };

            var Query = (from Q in Number select Q).Max();

            return Query;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    /// <summary>
    /// Get the average number of array
    /// </summary>
    /// <returns>int</returns>
    public static int AverageData()
    {
        try
        {
            int[] Number = { 4, 7, 3, 8, 6, 2, 6, 1, 5 };

            var Query = (from Q in Number select Q).Average(); 

            return (int)Query;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

}

Step 3
Call the above methods in Page Load event,it is look like this



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            Response.Write("Count :" + AggregateOperators.CountData().ToString() + "</br>");
            Response.Write("Sum :" + AggregateOperators.SumData().ToString() + "</br>");
            Response.Write("Min :" + AggregateOperators.MinData().ToString() + "</br>");
            Response.Write("Max :" + AggregateOperators.MaxData().ToString() + "</br>");
            Response.Write("Average :" + AggregateOperators.AverageData().ToString() + "</br>");  
             
        }
        catch (Exception)
        { 
        }
    }
}

Run the project

Download
Download Source Code

 

Saturday, September 18, 2010

ASP.net - Call server side function in Javascript(Client Side)

You cannot call server-side code directly from client-side code because the server side code executes at server side and client side code at the client. So whenever we have to call serverside code from javascript, you will need to use AJAX.


Another option is that you can call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page.


The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript.

So let see how to call server side function into client side(javascript).

Step 1
Create a Web Application and give the solution name as SolServerSidetoClinetSide.

Step 2
Drag and drop two textbox in a page.In this example we will accepting the sring from the user in one textbox and display the string in another textbox. it is look like this


<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" >
        </asp:ScriptManager>
        
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
                <asp:TextBox ID="txtReturnName" runat="server"></asp:TextBox><br />    
                
                 
          </ContentTemplate> 
        </asp:UpdatePanel>     

Add the attribute EnablePageMethods="true" to the ScriptManager.

Step 3
Write a method,GetName Which will accept the string from the user and return the string.this method as a PageMethod and then call this method GetName from client side code by using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method.it is look like this


 /// <summary>
    /// Get the Name from the user
    /// </summary>
    /// <param name="Name">Specify the Name</param>
    /// <returns>String</returns>
    
    [System.Web.Services.WebMethod]
    public static String GetName(String Name)
    {
        try
        {
            return Name; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

Remember one thing page methods needs to be static in code behind.In short methods must be a static.

Step 4
Create a javascript for call server side code.Add a javascript file called Jscript.js to your solution (Right Click Project -> Add New Item -> Jscript File).it is look like this

function OnError(Result, txtReturnName) {
    try {
        alert(Result.get_message());
    }
    catch (E)
    { }
    
}

function OnComplete(Result, txtReturnName) {
    try {

        var _txtReturnName = document.getElementById(txtReturnName);
        _txtReturnName.value = Result;

        alert('Server side function sucessfully called'); 
    }
    catch (E)
   { }
}

function OnCall(txtName,txtReturnName) {

    try {
        var _txtName = document.getElementById(txtName);
        
        // Call Server Side Method
        PageMethods.GetName(_txtName.value, OnComplete, OnError, txtReturnName);
    }   
    catch (E)
    { }

}

Step 5
Create a reference of javascript file from aspx page and invoke the OnCall method whenever the textbox loses focus.it is look like this

<head runat="server">
    <title>Server Side to Client Side</title>

    <script language="javascript" type="text/javascript" src="JScript.js"></script> 
   
</head>

Step 6
To invoke the methods whenever the textbox looses focus, Create a CallJavaScript Method in code behind and call this method in a Page_Load Event,it is look like this
 /// <summary>
    /// Call JavaScript
    /// </summary>
    private void CallJavaScript()
    {
        try
        {
            txtName.Attributes.Add("OnBlur", "OnCall('" + txtName.ClientID + "','" + txtReturnName.ClientID + "');");   
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }


protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                CallJavaScript(); 
            }
        }
        catch (Exception)
        { }
    }

Full Code

1. .aspx Code

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Server Side to Client Side</title>

    <script language="javascript" type="text/javascript" src="JScript.js"></script> 
   
</head>
<body>

    
      
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" >
        </asp:ScriptManager>
        
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
                <asp:TextBox ID="txtReturnName" runat="server"></asp:TextBox><br />    
                
                 
          </ContentTemplate> 
        </asp:UpdatePanel>     
    </div>
    </form>
</body>
</html>

2. JScript.js

function OnError(Result, txtReturnName) {
    try {
        alert(Result.get_message());
    }
    catch (E)
    { }
    
}

function OnComplete(Result, txtReturnName) {
    try {

        var _txtReturnName = document.getElementById(txtReturnName);
        _txtReturnName.value = Result;

        alert('Server side function sucessfully called'); 
    }
    catch (E)
   { }
}

function OnCall(txtName,txtReturnName) {

    try {
        var _txtName = document.getElementById(txtName);
        
        // Call Server Side Method
        PageMethods.GetName(_txtName.value, OnComplete, OnError, txtReturnName);
    }   
    catch (E)
    { }

}

3. .aspx.cs (Code Behind)

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                CallJavaScript(); 
            }
        }
        catch (Exception)
        { }
    }

    #region Methods
    /// <summary>
    /// Get the Name from the user
    /// </summary>
    /// <param name="Name">Specify the Name</param>
    /// <returns>String</returns>
    
    [System.Web.Services.WebMethod]
    public static String GetName(String Name)
    {
        try
        {
            return Name; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    /// <summary>
    /// Call JavaScript
    /// </summary>
    private void CallJavaScript()
    {
        try
        {
            txtName.Attributes.Add("OnBlur", "OnCall('" + txtName.ClientID + "','" + txtReturnName.ClientID + "');");   
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #endregion
}

Run the project.

Download
Download Source Code

Sunday, September 12, 2010

WPF - ControlTemplate in WPF

A control template is defined by using the ControlTemplate element that is placed inside the Resources element  Same as styles, control templates are type-specific, therefore can only be applied to elements that have the same type as the one defined.
You can change the structure and appearance of a control by modifying the ControlTemplate of that control.

Let see how to create a control template,in this article i am apply controltemplate on button control.

Step 1
Create a WPF Application and give the project name as SolControlTemplate.

Step 2
Add a button control on window,it is look like this


<Window x:Class="SolControlTemplate.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Control Template" Height="300" Width="300" Background="Gray">
    
      <Grid>
        <Button Name="BtnOK" Height="50" Width="100">OK</Button>
    </Grid>
</Window>

Step 3
Inside the window element add a Window.Resources Property,it is look like this

 <Window.Resources>
 </Window.Resources> 

Step 4
Inside the Window.Resources property add ControlTemplate element,it is look like this

<Window.Resources>
     <ControlTemplate x:Key="BtnTemplate" TargetType="Button">
     </ControlTemplate>
</Window.Resources>  

Step 5
Create a ControlTemplate on button control,it is look like this

 <Window.Resources>
        
        <ControlTemplate x:Key="BtnTemplate" TargetType="Button">
            <Grid>
            <Rectangle x:Name="ButtonRecTangle" Stroke="Black" StrokeThickness="3" RadiusX="10" RadiusY="10">
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                        <GradientStop Offset="0" Color="Coral"/>
                            <GradientStop Offset="1" Color="WhiteSmoke"/>
                    </LinearGradientBrush>
                </Rectangle.Fill> 
            </Rectangle>

                    <!--For Display Text(Content) in button -->
                <Viewbox>
                    <!--set the button text which user will define on button Ex- OK -->
                    <ContentControl Content="{TemplateBinding Button.Content}"></ContentControl>
                    
                </Viewbox>
            </Grid>
            
            <!--ControlTemplate Trigger-->
            
                        
        </ControlTemplate>

       
    </Window.Resources>  

Step 6
To apply a ControlTemplate trigger for button.ControlTemplate trigger property can write inside the ControlTemplate element,it is look like this

<ControlTemplate.Triggers>
                
                <!--Trigger apply on IsMouseOver-->
                
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter TargetName="ButtonRecTangle" Property="Fill">
                        
                        <Setter.Value>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                                <GradientStop Offset="0" Color="WhiteSmoke"/>
                                <GradientStop Offset="1" Color="Orange"/>
                            </LinearGradientBrush>
                        </Setter.Value> 
                        
                    </Setter>
                </Trigger>
                
                <!--Trigger apply on IsPressed-->
                
                <Trigger Property="Button.IsPressed" Value="True">
                    <Setter Property="RenderTransform">
                        <Setter.Value>
                            <ScaleTransform ScaleX=".9" ScaleY=".9"/>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="RenderTransformOrigin" Value=".5,.5"/>


   <Setter TargetName="ButtonRecTangle" Property="Fill">
                        <Setter.Value>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                                <GradientStop Offset="0" Color="Orange"/>
                                <GradientStop Offset="1" Color="Coral"/>
                            </LinearGradientBrush>
                        </Setter.Value> 
                    </Setter>
</Trigger> </ControlTemplate.Triggers> </ControlTemplate>

Finally ControlTemplate element look like this

 <Window.Resources>
        
        <ControlTemplate x:Key="BtnTemplate" TargetType="Button">
            <Grid>
            <Rectangle x:Name="ButtonRecTangle" Stroke="Black" StrokeThickness="3" RadiusX="10" RadiusY="10">
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                        <GradientStop Offset="0" Color="Coral"/>
                            <GradientStop Offset="1" Color="WhiteSmoke"/>
                    </LinearGradientBrush>
                </Rectangle.Fill> 
            </Rectangle>

                    <!--For Display Text(Content) in button -->
                <Viewbox>
                    <!--set the button text which user will define on button Ex- OK -->
                    <ContentControl Content="{TemplateBinding Button.Content}"></ContentControl>
                    
                </Viewbox>
            </Grid>
            
            <!--ControlTemplate Trigger-->
            
            <ControlTemplate.Triggers>
                
                <!--Trigger apply on IsMouseOver-->
                
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter TargetName="ButtonRecTangle" Property="Fill">
                        
                        <Setter.Value>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                                <GradientStop Offset="0" Color="WhiteSmoke"/>
                                <GradientStop Offset="1" Color="Orange"/>
                            </LinearGradientBrush>
                        </Setter.Value> 
                        
                    </Setter>
                </Trigger>
                
                <!--Trigger apply on IsPressed-->
                
                <Trigger Property="Button.IsPressed" Value="True">
                    <Setter Property="RenderTransform">
                        <Setter.Value>
                            <ScaleTransform ScaleX=".9" ScaleY=".9"/>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="RenderTransformOrigin" Value=".5,.5"/>
                     <Setter TargetName="ButtonRecTangle" Property="Fill">
                        <Setter.Value>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                                <GradientStop Offset="0" Color="Orange"/>
                                <GradientStop Offset="1" Color="Coral"/>
                            </LinearGradientBrush>
                        </Setter.Value> 
                    </Setter>
               </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
</Window.Resources>

Step 7
To apply ControlTemplate on button control,it is look like this

<Grid>
        <Button Name="BtnOK" Height="50" Width="100" Template="{StaticResource BtnTemplate}">OK</Button>
</Grid>


Full Code



<Window x:Class="SolControlTemplate.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Control Template" Height="300" Width="300" Background="Gray">
    
    <Window.Resources>
        
        <ControlTemplate x:Key="BtnTemplate" TargetType="Button">
            <Grid>
            <Rectangle x:Name="ButtonRecTangle" Stroke="Black" StrokeThickness="3" RadiusX="10" RadiusY="10">
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                        <GradientStop Offset="0" Color="Coral"/>
                            <GradientStop Offset="1" Color="WhiteSmoke"/>
                    </LinearGradientBrush>
                </Rectangle.Fill> 
            </Rectangle>

                    <!--For Display Text(Content) in button -->
                <Viewbox>
                    <!--set the button text which user will define on button Ex- OK -->
                    <ContentControl Content="{TemplateBinding Button.Content}"></ContentControl>
                    
                </Viewbox>
            </Grid>
            
            <!--ControlTemplate Trigger-->
            
            <ControlTemplate.Triggers>
                
                <!--Trigger apply on IsMouseOver-->
                
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter TargetName="ButtonRecTangle" Property="Fill">
                        
                        <Setter.Value>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                                <GradientStop Offset="0" Color="WhiteSmoke"/>
                                <GradientStop Offset="1" Color="Orange"/>
                            </LinearGradientBrush>
                        </Setter.Value> 
                        
                    </Setter>
                </Trigger>
                
                <!--Trigger apply on IsPressed-->
                
                <Trigger Property="Button.IsPressed" Value="True">
                    <Setter Property="RenderTransform">
                        <Setter.Value>
                            <ScaleTransform ScaleX=".9" ScaleY=".9"/>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="RenderTransformOrigin" Value=".5,.5"/>



                    <Setter TargetName="ButtonRecTangle" Property="Fill">
                        <Setter.Value>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                                <GradientStop Offset="0" Color="Orange"/>
                                <GradientStop Offset="1" Color="Coral"/>
                            </LinearGradientBrush>
                        </Setter.Value> 
                    </Setter>
</Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Window.Resources> <Grid> <Button Name="BtnOK" Height="50" Width="100" Template="{StaticResource BtnTemplate}">OK</Button> </Grid> </Window>

Run the project.

Output

1.ControlTemplate Button

























Click on image for better view

2.When user move the mouse pointer on button control

























Click on image for better view

3.When user press the button

























Click on image for better view

Download
Download Source Code