Tuesday, May 29, 2012

Find Child Control from ControlTemplate in Silverlight

In Silverlight application development sometimes you need to find ControlTemplates Child control from silverlight control.

Below is code that will return child control from TemplateChild of passed parent DependencyObject.

 public static FrameworkElement GetTemplateChildByName
       (DependencyObject parent, string name)
 {
    int childnum = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < childnum; i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);
        if (child is FrameworkElement && 
                ((FrameworkElement)child).Name == name)
        {
           return child as FrameworkElement;
        }
        else
        {
           var s = GetTemplateChildByName(child, name);
           if (s != null)
             return s;
        }
    }
    return null;
 }

Above method will return passed named child control from parent control.

Here is the code that call GetTemplateChildByName method.

 private void TabHeaderBackgroundBorder_MouseLeftButtonUp
                (object sender, MouseButtonEventArgs e)
 {
    FrameworkElement selectedItem = TabHeader as FrameworkElement;
    FrameworkElement TabPanel= 
           GetTemplateChildByName(selectedItem, "MyTabContentPanel");
    FrameworkElement parentBorder = 
           GetTemplateChildByName(TabPanel, "parentBorder");
            
 } 

In above code, I am finding ScalePanel from TabHeader Items and finding Border within ScalePanel.

so yon can find Hierarchy of control from parent control.

Thursday, May 24, 2012

Convert Hexa string to Color in Silverlight

Below method will convert Color from Hexa string.

 public static Color GetColorFromHexa(string hexaColor)
 {
    if (string.IsNullOrEmpty(hexaColor))
                return Colors.Transparent;
    if (hexaColor.Length == 9)
    {
       return Color.FromArgb(
        Convert.ToByte(hexaColor.Substring(1, 2), 16),
        Convert.ToByte(hexaColor.Substring(3, 2), 16),
        Convert.ToByte(hexaColor.Substring(5, 2), 16),
        Convert.ToByte(hexaColor.Substring(7, 2), 16));
    }
    else if (hexaColor.Length == 7)
    {
        return Color.FromArgb(
         Convert.ToByte("FF", 16),
         Convert.ToByte(hexaColor.Substring(1, 2), 16),
         Convert.ToByte(hexaColor.Substring(3, 2), 16),
         Convert.ToByte(hexaColor.Substring(5, 2), 16)
        );
    }
    else
    {
        return Colors.Transparent;
    }

 }

I have created method that convert hexa string to SolidColor.Color value.

If i am passing Hexa string to 7 cahracter then it will add  first two character for opacity.

so above method will return SolidColor.Color value from Hexa string

Monday, May 21, 2012

LINQ to SQL Query Examples

Please refere below MSDN link, you can find lots of examples with explanation.

LINQ to SQL Query Sample

Below link for only LINQ samples.

LINQ Examples 

Friday, May 18, 2012

Silverlight : Creating and Using Service Oriented Architecture in Silverlight

Service Oriented Architecture is a methodologies for  development and integration where functionality is grouped  and packaged as interoperable services.

In this post we go through creating custom response and request classes that use to get response from service and convert it to response type.

I have created sample that convert JSON result to DataContract ( passed generic types).
I have used Newtonsoft.Json dll to Deserialize JSON value.

Step 1 : Create Request Class.

 public class MyRequest
 {
    public List<KeyValuePair<string, string>> Parameter { get; set; }
 }

this class used as request for method that have list of  parameters.

Step 2 : Create Class for ResponseType.

 public enum MyResponseType
 {
        SUCCESS,
        ERROR       
 }

Step 3 : Create Class for Response
 
public class MyResponse<T>
{
    public String ResponseType { get; set; }
    public T Data { get; set; }
}

This class will return result of type passed (generic type),
ResponseType parameter will return Success or Error while getting response from service
Data parameter return data converted to passed Type.

Step 4 :Create Service Helper class and into that class Create Method that have Request and Response as a Parameter.
 
public class MyServiceHelper 
{
 
  public string URL { get; set; } 
  public MyServiceHelper(string uri)
  {
    URL=uri; 
  }
  public void CallJSON<T>(string methodName, List<KeyValuePair<string, string>> parameter,
         Action<MyResponse<T>> callbackMethod)
  {
      CallMethod<T>(methodName, parameter, callbackMethod);
  }
 
  public void CallMethod<T>(string methodName, List<KeyValuePair<string, string>> parameter,
          Action<MyResponse<T>> callbackMethod)
  {
      WebClient client = new WebClient();
      client.Headers["contentType"] = "application/json; charset=utf-8";      

      string fullUrl = 
          AppendQueryStringToUrl(URL + methodName, parameter);
      client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_WebRequestCompleted<T>);
      client.OpenReadAsync(new Uri(fullUrl), callbackMethod);
      break;

  }
  void client_WebRequestCompleted<T>(object sender, 
            System.ComponentModel.AsyncCompletedEventArgs e)
  {
     var result = new MyResponse<T>();
     if (e.Error != null)
     {
         result.ResponseType = MyResponseType.ERROR.ToString();             
     }
     else if (e is UploadStringCompletedEventArgs)
     {
         result = JsonConvert.DeserializeObject<MyResponse<T>>(((UploadStringCompletedEventArgs)e).Result);
     }
     else
     {
         StreamReader reader = new StreamReader(((OpenReadCompletedEventArgs)e).Result);
         string strResult = reader.ReadToEnd();
         result = JsonConvert.DeserializeObject<MyResponse<T>>(strResult);
     }
     Action<MyResponse<T>> responseResult= (Action<MyResponse<T>>)e.UserState;
     responseResult(result);
  }
  public string AppendQueryStringToUrl(string url, List<KeyValuePair<string, string>> parameters)
  {
    StringBuilder combinedParams = new StringBuilder();
    if (parameters != null)
    {
       parameters.ForEach((parameter) =>
       {
           combinedParams.AppendFormat("&{0}={1}", parameter.Key, 
                         HttpUtility.UrlEncode(parameter.Value));
       });
       if (combinedParams.Length > 0)
       {
           combinedParams.Replace("&", "?", 0, 1);
       }
    }
    return url + combinedParams.ToString();
  } 
} 

As shown in above code, first i have created CallJSON method that contains methodname, list of paramters and callback response that targeted to Action result.

In CallMethod<T> method, i have created object WebClient class.
WebClient is used to call service Url with querystring parameter and it has Header contenttype.
Header ContentType carry content type info that specify which type of result are you getting from service.

In client_WebRequestCompletedMethod<T> we are getting response of JSON string.

Now we have to Deserialize JSON value to Type of <T> generic class provided in response type.

Step 5 : Create Generic Class for result

   [DataContract]
    public class Employee
    {
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string LastName { get; set; }
        [DataMember]
    }

Step 6 : Call ServiceHelper Method to Get Response

 private void GetSiteDownInfoList()
 {            
     List<Employee> empList=new List<Employee>();
     MyServiceHelper service = new MyServiceHelper("http://localhost/EmployeeService");
     List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>();
     data.Add(new KeyValuePair<string, string>("userid", "1"));
 
     service.CallJSON<List<Employee>>("GetEmployees", data, (response) =>
     {
         if (response.ResponseType.ToString().Equals(MyResponseType.SUCCESS.ToString()))
         {
             response.Data.ForEach(t => empList.Add(t));
         }

     });
           
  }

So, this way you can create your own reusable class for your application.
 

Thursday, May 17, 2012

Windows Phone 7 : Unit Testing (Create Test Project)

To Create Test Project in windows phone 7, you require to install NuGet and Windows Phone Test Project Templates.

It is a Visual Studio extension that makes it easy to install third-party libraries and tools in Visual Studio.

WP7Essentials library is used to create WindowsPhoneEssentials.Testing project that contains Silverlight Unit Test Framework which has been updated for use with Mango, as well as a few testing helpers.

Let’s go through Step by steps.

Step 1 :Download and  Install NuGet.

    Click NuGet.org To Download NuGet.
  
Step 2 : Download and Install Windows Phone Test Project Template.


   Click WP7 Test Project Template To Download phone test project template.

 
Step 3 : Create Windows Phone Test Project.

After installing NuGet and WP7 test project template, Start with creating new test project.
Open Visual studio and click on New Project.

In New Project dialog left panel select Test from Installed Template.

There are two items listed Test Project and Windows Phone Test Project as in below screen.

Select Windows Phone Test Project and click OK button.


your Project solution Explorer look like below screen.


When you build you project it gives error related to assembly missing (Microsoft.Silverlight.Testing , Microsoft.VisualStudio.TestTools.UnitTesting)

For that we have to use NuGet to get the latest versions of either Silverlight Unit Test Framework for Windows Phone (No Mango Support yet!) or Windows Phone Essentials Testing.

Step 4 : Install WindowsPhoneEssentials.Testing Package.

Click on Tools Menu and select Manage NuGet packages from Library Package Manager as in below screen.


Manage NuGet Packages Dialog will opened.

In this dialog, Search windowsphoneessentials from Search Online Textbox.
 it gives a list of packages, select WindowsPhoneEssentials.Testing item from the list and click on Install button (See below image).


it will install packages in current project, now close the dialog.

Now expand references in project, few assemblies are added into project reference (see image below).


As shown in above image, highlighted assemblies are added into reference and also one package.config file added into project.


Now Build you project, it build succeeds.
Run the Application, you testcase run within 5 seconds and you will get result (see below image).




Conclusion

In this way you can create you own Test Project using NuGet and WindowsPhoneEssentials Package.

Thursday, May 10, 2012

Diffrerence Between LEN and DATALENGTH in SQL Server

LEN function removes trailing spaces of string while DATALENGTH consider trailing spaces.

Below is Example.

CREATE TABLE #tmp (h1 varchar(10))
GO
INSERT INTO #tmp VALUES ('abc ')
INSERT INTO #tmp VALUES ('abc')
GO
SELECT LEN(h1) as 'LEN(EqualWithSpace)',DATALENGTH(h1) as 'DATALENGTH(EqualWithSpace)', * FROM #tmp WHERE h1 = 'abc '
SELECT  LEN(h1) as 'LEN(LikeWithSpace)', DATALENGTH(h1) as 'DATALENGTH(LikeWithSpace)', * FROM #tmp WHERE h1 LIKE 'abc %'
SELECT  LEN(h1)as 'LEN(LikeNoSpace)', DATALENGTH(h1) as 'DATALENGTH(LikeNoSpace)', * FROM #tmp WHERE h1 LIKE 'abc%'

GO
DROP TABLE #tmp 
 

This is the output of above select statements.


Creating Comparer in C# to Get Distinct values from Generic Collection

First Create class


  public class GlassType
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }
    } 

Now Create one comparer custom class to check for distinct value by ID

 public class UserComparer : IEqualityComparer<GlassType>
 {
      public bool Equals(GlassType x, GlassType y)
      {
         return (x.Id == y.Id);
      }
      public int GetHashCode(GlassType x)
      {
         return (x.Id.GetHashCode());
      }
 }


In above colde i have created custom class that filters distinct values from generic collection.


Then Create one property in your class that has collections of GlassType

private ObservableCollection<GlassType> glassTypeList;
public ObservableCollection<GlassType> GlassTypeList
{
   get { return glassTypeList; }
   set
   {
       if (glassTypeList != value)
       {
          glassTypeList = value;
          RaisePropertyChanged(() => GlassTypeList);
       }
   }
}

Using UserComparer get Distinct values.

var Result; //Result contains list of GalssType retrive from service

 GlassTypeList = new ObservableCollection<GlassType>
       (Result.Select(x => x.GlassType).Distinct(new UserComparer()).ToList()); 

Creating and Using Collections in Silverlight

First Create generic Collection class as per your requirement in development.


public class MilesCollection : ObservableCollection<Miles>
    {
        public MilesCollection()
        {
            this.Add(new Miles(1, "1 Miles"));
            this.Add(new Miles(2, "2.5 Miles"));
            this.Add(new Miles(3, "5 Miles"));
            this.Add(new Miles(4, "10 Miles"));
        }
        public static Miles FromId(Int32 Id)
        {
            return new MilesCollection().Where(x => x.Id == Id).Single();
        }
    }
    public class Miles
    {
        public Miles()
        {

        }
        public Miles(Int32 id, String val)
        {
            Id = id;
            Value = val;
        }
        public Int32 Id { get; set; }
        public String Value { get; set; }

        public bool Equals(Miles mile)
        {
            return Id == mile.Id;
        }
    } 

as shown in above i have created Miles class and MilesCollection class that inherits from collection of Miles.

Now use your collection in UserControl or Page

<UserControl x:Class="TestApplication.Views.MileView"
       xmlns:collections="clr-namespace:TestApplication.Collections">
 
 
<ComboBox  DisplayMemberPath="Value">
           <ComboBox.ItemsSource>
               <collections:MilesCollection  />
            </ComboBox.ItemsSource
</ComboBox> 


Friday, May 4, 2012

How to Create C# Code Snippet in Visual Studio 2010

Visual studio provides some inbuilt IntelliSense Code Snippets for Expansion, SurroundsWith and Refactoring.


When you have some piece of code and you need to use each and every file, instead of rewriting you can create you own code snippet.

that will saves your times to rewriting block of code.

IntelliSense Code Snippets created in XML file.

There are Three Snippet types available.

   1. Expansion
   2. SurroundsWith 
   3. Refactoring

In this post I am going to create Expansion Code Snippet for Property block with MVVM functionality that is RaisePropertyChanged.

Step 1 : First Create XML file in Visual Studio 2010 and save file as propmvvm.snippet.


<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">

Code Snippet file start with CodeSnippets element which has xmlns attribute for snippet.


Step 2 : Add CodeSnippet Section under root(CodeSnippets) section
 <?xml version="1.0" encoding="utf-8"?>
 <CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">

Step 3 : Add Header Section within CodeSnippet Section.
    <Header>
      <Title>propmvvm</Title>
      <Shortcut>propmvvm</Shortcut>
      <Description>
        Code snippet for property with raisepropertychanged event
      </Description>
      <Author>Microsoft</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>


This section has elements like Title, shortcut for IntelliSense and Description.

when you type using IntelliSens it will shows list of snippet including which you have created with given shortcut.

Description element shows detailed description of snippet on MouseOver of you snippet.

SnippetType  describes which type of snippet are you going to create like Expansion(prop) or SurroundWith (try/catch).

Step 4 : Add Snippet section and add Declaration Section within Snippet tag.

<Snippet>
   <Declarations> 
   ......
   ......
   </Declaration>
<Snippet> 
      

Step 5 : Create Literals or Objects within Declaration Section.
<Declarations> 
   <Literal>
          <ID>type</ID>
          <ToolTip>Property Type</ToolTip>
          <Default>int</Default>
   </Literal>
   <Literal>
          <ID>property</ID>
          <ToolTip>Property Name</ToolTip>
          <Default>MyProperty</Default>
   </Literal>
   <Literal>
          <ID>field</ID>
          <ToolTip>The variable baking this property</ToolTip>
          <Default>MyVariable</Default>
   </Literal>
</Declaration>
 

Literal Element are editable values that are inserted by user into snippet.
In above code I have created Three Literals.

First Literal describes Type of property or variable, i have set Default value to int ( you can give any datatypes including (double, bool ,string etc.)

Second Literal element is for editable name of Property.

Third Literal element has field, user can gives any variable name that used within property Get/Set.

Step 6 : Create Code Element within Snippet section, Inside the Code element, add the C# code for the snippet.

   <Code Language="CSharp">
        <![CDATA[private $type$ $field$;

 public $type$ $property$
 {
  get { return $field$;}
  set { $field$ = value;
    RaisePropertyChanged("$property$");
    }
 }
 $end$]]>
 

This section describes actual code in C# for snippet,
In code section first you have to set Language in which you are going to create snippet.
In this section we are using Declaration Literals  type,fields and property name.

Below is  Full source Code of Property block Snippet

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>propmvvm</Title>
      <Shortcut>propmvvm</Shortcut>
      <Description>Code snippet for property with raisepropertychanged event</Description>
      <Author>Microsoft</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>type</ID>
          <ToolTip>Property Type</ToolTip>
          <Default>int</Default>
        </Literal>
        <Literal>
          <ID>property</ID>
          <ToolTip>Property Name</ToolTip>
          <Default>MyProperty</Default>
        </Literal>
        <Literal>
          <ID>field</ID>
          <ToolTip>The variable baking this property</ToolTip>
          <Default>MyVariable</Default>
        </Literal>
      </Declarations>
      <Code Language="CSharp">
        <![CDATA[private $type$ $field$;

 public $type$ $property$
 {
  get { return $field$;}
  set { $field$ = value;
    RaisePropertyChanged("$property$");
    }
 }
 $end$]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Your Snippet is created. no how to import snippet in Visual Studio.

Import Snippet in Visual Studio.

Step 1 : Go to Tools Menu and click on Code Snippets Manager item.


it will open Code Snippets Manager dialog as shown in below image.




 Step 2 : Click on Import.. Button and select your snippet file, it will ask for selection location for snippets as below screen.


Select location for snippets and click on Finish button, your code snippet imported successfully.
Now you can use your snippet in development.

Using Snippets in C# 
Create class file in your project.
In that file start typing with you snippet shortcut.
it will display  list of IntelliSense code snippets including your snippet




 As shown in above image, you have list of snippets with your created snippet.
when select snippet as you created it gives popup with description of snippet as you have written in Header section of snippet XML file.
Now Select you snippet it will insert block of code as in blow image.




 Now change type which you want for property it will automatically change type all the places in you block.
same as when you change variable name , it will automatically change variable in Get/Set of property block.
In this way you can create you own snippets.


Conclusion
So by using snippets you saves lots of time of rewriting piece of code. 



Thursday, May 3, 2012

Customize DomainUpDown control in Silverlight

Introduction

DomainUpDown control is silverlight toolkit control, this control allows user to spin(up/down) through collection of objects.

To work with domainupdown control, first you have to download silverlight latest toolkit from Silverlight Toolkit  and install.
In this post we walk-through how to change appearance of  DomainUpDown control.

Walk-through step by step

you can find DoaminUpDown control from System.Windows.Controls.Input.Toolkit. So first add reference of System.Windows.Controls and System.Windows.Controls.Input.Toolkit.


I have customize DomainUpDown control as shown in above snap as i am binding ImageList with name as ItemsSource to the control.

Step 1: First Start with Data,Create XML file that contains data collections

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <natures>
    <natureview id = "1" title = "Mountain" 
      imagesource="/DomainUpDownCustomization;component/Images/Mountain.jpg" />
    <natureview id = "2" title = "Sunset"  
      imagesource="/DomainUpDownCustomization;component/Images/Sunset.jpg" />
    <natureview id = "3" title = "Tulips-photo" 
      imagesource="/DomainUpDownCustomization;component/Images/tulips-photo.jpg"/>
    <natureview id = "4" title = "Waterfalls"  
      imagesource="/DomainUpDownCustomization;component/Images/Waterfalls_64.jpg"/>
  </natures>
  
</root>
 
I have created Service Oriented Architecture in this application, like creating Request/Response class.

Step 2 : Create Entity that holds data collection
 

public class Nature
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string ImageSource { get; set; }
    } 
 
storing image collection from XML files to Nature Collection.

Step 3: Create Response class that return Nature collections
 
   public class GetNatureResponse : Response
    {
        public IEnumerable<Nature> NatureCollection { get; set; }

        public GetNatureResponse(IEnumerable<Nature> natureCollection)
        {
            NatureCollection = natureCollection;
        }

    }
    public class Response
    {
        public bool IsSuccess { get; set; }
    } 
 
Above class holds collections of Natures.

Step 4: Create ServiceHelper class to get data from XML and bind into Entity

   public class NatureServiceHandler
    {
        public static void GetNaturePictures(GetRequest request, 
                         Action<GetNatureResponse> callback)
        {
            StreamResourceInfo resources = 
                Application.GetResourceStream(new Uri("Data/Nature.xml", UriKind.Relative));
            XDocument document = XDocument.Load(resources.Stream);

            IEnumerable<Nature> result = from doc in document.Descendants("natureview")
                  select new Nature
                  {
                     Id = Convert.ToInt32(doc.Attribute("id").Value),
                     Title = doc.Attribute("title").Value,
                     ImageSource = doc.Attribute("imagesource").Value
                  };

            callback(new GetNatureResponse(result));
        }
    }

This Service Helper class returns data collection retive from XML files. Result will return in callback.
now, create wrapper class for Nature class (i.e. NatureViewModel) which contains properties of Nature class.

Step 5 :Create ViewModel for UI

public class NatureCollectionViewModel : ViewModelBase
    {      

        private ObservableCollection<NatureViewModel> _natures;
        public ObservableCollection<NatureViewModel> Natures
        {
            get { return _natures; }
            set
            {
                if (_natures != value)
                {
                    _natures = value;
                    RaisePropertyChanged(() => Natures);
                }
            }
        }
        private NatureViewModel _selectedNature;
        public NatureViewModel SelectedNature
        {
            get { return _selectedNature; }
            set
            {
                if (_selectedNature != value)
                {
                    _selectedNature = value;
                    RaisePropertyChanged(() => SelectedNature);
                }
            }
        }
        private NatureTypes _natureType;
        public NatureTypes NatureType
        {
            get { return _natureType; }
            set
            {
                if (_natureType != value)
                {
                    _natureType = value;
                    RaisePropertyChanged(() => NatureType);
                    SelectedNature = Natures[Convert.ToInt16(_natureType)];
                }
            }

        }

        public NatureCollectionViewModel()
        {
            Natures = new ObservableCollection<NatureViewModel>();
             NatureServiceHandler.GetNaturePictures(
                new GetRequest(),
                (response) =>
                {
                    foreach (var item in response.NatureCollection)
                    {
                        Natures.Add(new NatureViewModel(item));
                    }

                    if (Natures.Count > 0)
                    {
                        SelectedNature = Natures[Convert.ToInt32(NatureType)];
                    }
                });
        }

    } 
 
In Default Constructor i am calling ServiceHanlder clas by passing request and bind Nature collection property with response result.

Step 6: Switch to UI, add InputToolkit and LayoutToolkit namespance.
 
<UserControl x:Class="DomainUpDownCustomization.View.NatureCollectionView"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   mc:Ignorable="d"           
   xmlns:layoutToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Layout.Toolkit"
   xmlns:inputToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"> 

InputToolkit contain DomainUpDownControl and LayoutToolkit has TransitioningContentControl .
To format layout for both control i have added reference of this toolkit dlls.

Step 7 : Craeate DomainUpDown control in your Page

 <inputToolkit:DomainUpDown Grid.Row="1"                                  
              ItemsSource="{Binding Natures}"
              Value="{Binding SelectedNature, Mode=TwoWay}"
              IsCyclic="True"
              x:Name="NatureDomainControl"
              Height="360"
              Style="{StaticResource DomainUpDownStyle}"
              HorizontalAlignment="Center"
              Width="645"
              Margin="0,0,0,0"
              IsEditable="False"
              BorderBrush="Black">
          
            <inputToolkit:DomainUpDown.ItemTemplate>
                <DataTemplate>
                   .......
                   ....... 
                </DataTemplate>
            </inputToolkit:DomainUpDown.ItemTemplate>
        </inputToolkit:DomainUpDown> 

In above snippet, i am binding Nature Collection as a ItemsSource to DomainUpDown and binding properties like images in child control.

Step 8:Now move to styles, creating TransitioningContentControl style

 <Style x:Key="TransitioningContentTranslation"
               TargetType="layoutToolkit:TransitioningContentControl">
            <Setter Property="IsTabStop"
                    Value="True" />
            <Setter Property="HorizontalContentAlignment"
                    Value="Left" />
            <Setter Property="VerticalContentAlignment"
                    Value="Top" />
            <Setter Property="Transition"
                    Value="DefaultTransition" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="layoutToolkit:TransitioningContentControl">                        
                              
                            .......

 
To understand animation first you have to know what is VisualStateManager.
it Manages states and the logic for transitioning between states for controls. like (Normal,MouseOver,Focus) these are VisualStates.

StoryBoard is used for animation with a timeline,
if you want animate control on MouseOver of control than you can place storyborad within MouseOver VisualState.

Created VisualState for each ContentControl,VisualState is used to Transition content on Up/Down state.

Step 9:Creating Button Spinner Style 

<Style x:Key="ButtonSpinnerStyle"
               TargetType="inputToolkit:ButtonSpinner">
               .......
               .......
                Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="inputToolkit:ButtonSpinner">
                        <Grid>
                            <Grid.Resources>
                                <ControlTemplate x:Key="IncreaseButtonTemplate"
                                                 TargetType="RepeatButton">
 
                          .......
                          .......
 
button spinner style is used to change spin button image or path. i have created two templates one for Increase button and another for Descrease button.

you can create you own path or image for the buttons, currently i have created path  ( > ) for increase button and  (< ) for decrease button.

I have set Double Animation for each button.

Step 10: Create DomainUpDown style

<Style x:Key="DomainUpDownStyle"
               TargetType="inputToolkit:DomainUpDown">
           .......
           .......
   <Setter Property="Template">
       <Setter.Value>
          <ControlTemplate TargetType="inputToolkit:DomainUpDown">
             <Grid x:Name="RootElement"
                              Width="670">                            
                <Border x:Name="Border"
                    Opacity="1"
                    Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}"
                    Padding="{TemplateBinding Padding}"
                    CornerRadius="1"
                    IsHitTestVisible="True"
                    <Border x:Name="MouseOverBorder"
                          BorderBrush="Transparent"
                          BorderThickness="1"
                          IsHitTestVisible="True">
                          <inputToolkit:ButtonSpinner x:Name="Spinner"
                            HorizontalAlignment="Stretch"
                            VerticalAlignment="Stretch"
                            HorizontalContentAlignment="Stretch"
                            VerticalContentAlignment="Stretch"
                            Style="{StaticResource ButtonSpinnerStyle}"
                            IsTabStop="False"
                            TabIndex="3">
                            <Grid>
                               <layoutToolkit:TransitioningContentControl x:Name="Visualization"
                                  Style="{StaticResource TransitioningContentTranslation}"
                                  IsTabStop="False"
                                  HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                  VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                  Content="{TemplateBinding Value}"
                                  ContentTemplate="{TemplateBinding ItemTemplate}"
                                  FontFamily="{TemplateBinding FontFamily}"
                                  FontSize="{TemplateBinding FontSize}"
                                  FontStretch="{TemplateBinding FontStretch}"
                                  Foreground="{TemplateBinding Foreground}" />
                            </Grid>
                          </inputToolkit:ButtonSpinner>
                       </Border>
                </Border>
                 ......
                 ......
             </Grid>
          </ControlTemplate>
       </Setter.Value>
   </Setter>
</Style>
 

I am setting styles of Button spinner and TransitioningContentControl that was previously created in this article.
In this way you can change style of any control using modifying ControlTemplate.

You can download source from below link.

Click DomainUpDownControlCustomization To Donwload Source.

  

Windows Phone 7 : Custom Themes (Load ResourceDictionary dynamically)

To change theme In windows phone 7, you can change background and accent colors from settings.

In WP7 development sometimes we require to create our own styles for application.

In this case we can create multiple resource Dictionary and apply on change of application accent color.

In this post we walk trough how to create custom themes and add dynamically on Application theme change.



I have created Three Themes Blue,Magenta and Default.

Step 1 : First Create ResourceDictionaries for Different themes and add styles for controls.

Blue.xaml

 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:System="clr-namespace:System;assembly=mscorlib">
    <Style x:Key="CommonBackgroundStyle"
           TargetType="Image">
        <Setter Property="Stretch"
                Value="None" />
        <Setter Property="Source"
                Value="/CustomThemeInWP7;component/Images/blue.png" />
    </Style>
    <Style TargetType="Button"
           x:Key="CommonButtonStyle">
        <Setter Property="HorizontalContentAlignment"
                Value="Center" />
        <Setter Property="VerticalContentAlignment"
                Value="Center" />
        <Setter Property="Margin"
                Value="5" />
        <Setter Property="Height"
                Value="70" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="Pressed">
                                    <Storyboard>
                                       .....
                                       ..... 
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border CornerRadius="10"
                                BorderBrush="Black"
                                BorderThickness="2"
                                Opacity="0.9"
                                x:Name="BackgroundBorder">
                            <Border.Background>
                                <LinearGradientBrush StartPoint="0,1"
                                                     EndPoint="1,1">
                                    <GradientStop Color="#0055FF"
                                                  Offset="0" />
                                    <GradientStop Color="#0E38E2"
                                                  Offset="5" />
                                    <GradientStop Color="#1640EA"
                                                  Offset="8" />
                                </LinearGradientBrush>
                            </Border.Background>
                        </Border>
                        <ContentPresenter Content="{TemplateBinding Content}"
                               HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                               VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

In Above snippet i have created styles for Image and Button for blue theme.

Step 2 : Same way create more resource Dictionary for other themes.

Step 3 : Apply created styles to controls in page.

MainPage.xaml

<Grid x:Name="LayoutRoot"
          Background="Transparent">
        <Image Style="{StaticResource CommonBackgroundStyle}" />
        <Grid HorizontalAlignment="Center"
              VerticalAlignment="Center">
            <StackPanel Orientation="Horizontal">
                <Button Content="OK"
                        Width="160"
                        Style="{StaticResource CommonButtonStyle}" />
                <Button Content="CANCEL"
                        Width="160"
                        Style="{StaticResource CommonButtonStyle}" />
            </StackPanel>
        </Grid>
 </Grid>


Step 4 : In constructor of App.xaml.cs write code to load resource Dictionary dynamically.


   public App()
   {
           
      UnhandledException += Application_UnhandledException;
      InitializeComponent();           
      InitializePhoneApplication();
           
      if (System.Diagnostics.Debugger.IsAttached)
      {               
          Application.Current.Host.Settings.EnableFrameRateCounter = true;            
               
          PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
      }
 



      //load resource dictionary daynamically
      var dictionaries = Resources.MergedDictionaries;
      dictionaries.Clear();
      string source = "";
      SolidColorBrush selectedTheme = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
      SolidColorBrush blueBrush = 
              new SolidColorBrush() { Color = new Color() { A = 255, R = 27, G = 161, B = 226 } };
      SolidColorBrush magentaBrush =
              new SolidColorBrush() { Color = new Color() { A = 255, R = 216, G = 0, B = 115 } };
      if (selectedTheme.Color == blueBrush.Color)
      {
          source = String.Format("/CustomThemeInWP7;component/Themes/Blue.xaml");
      }
      else if (selectedTheme.Color == magentaBrush.Color)
      {
          source = String.Format("/CustomThemeInWP7;component/Themes/Magenta.xaml");
      }
      else
      {
          source = String.Format("/CustomThemeInWP7;component/Themes/Default.xaml");
      }
      var theme = new ResourceDictionary { Source = new Uri(source, UriKind.Relative) };
      dictionaries.Add(theme);
   }
 

In above code, first i get selected Accent Color  of application. then i am checking if color is blue, i will add Bule.xaml resource dictionary to Application.Current.Resources.MergeDictionaries.

if color is Magenta, i will add Magenta.xaml resource dictionary to Application.Current.Resources.MergeDictionaries.

else Default theme is applied.

So this way you can load resourceDictionary dynamically at runtime.

you can download code from below link.

Click WP7 Custom Theme To Download Source code.