Thursday, January 31, 2013

Overcome Style Property


Problem:
                I have a Silverlight project that is created MVVM pattern. I have created many style with key and some kind of style what i am created Are global that target type such as Target Type="Silverlight Control". In this case i cannot overcome some property which is no need in my Page.  How can i solve this?
Solution:
                If you have a textbox style like below
You can write code by this syntax
<TextBox Margin="0"/>

Wednesday, January 30, 2013

Difference between dependency property & normal property

DependencyProperty

  1. Dependency Property is a property which register another property, It is depend on not itself but depend on (for e.g.  xaml binding ) external inputs .
  2. Dependency Property is set to enable declarative code to alter the properties of an object which reduces the data requirements by providing a more powerful notification system regarding the change of data in a very specific way
  3. DependencyProperty.Register() method contain the Propertymetadata objects that stores the default value of the property. It may be also null.
  4. DependencyProperty should be register to  the normal CLR property  with Register() method by passing the property field that you use to store the data.
  5. Dependency Property can also contain the property changes notification . Using the CallBack() while registering the property can send the notification to user when the value has been chaged 
CLR Property
  1. CLR Property   Is a Classic .NET Class property. It is a normal property Which is nothing but a cross connection between fields & methods.
  2. CLR Property        Is the normal property which doesn’t have more functionality like dependency property. It is  wrapped only with get and set  arrangement to be able to retrieve and update a private member.
  3. CLR Property Need not to carry any default value .
  4. CLR property  Need to not to register with any property, it is straight forward.
  5. CLR Property    Don’t have any Notification  system.

Difference between Styles & Template

Styles

  1. Styles can be used with any Silverlight Elements that is derived from Framework Element .
  2. By using Styles , u can modify the default values of properties of the control to which the style is applied .
  3. The Properties values in styles can be Overridden by the values that are set on the control itself when it is drawn in the artboard .
  4. Within a style u can only modify pre-existing properties of the Control.
  5. Using Styles u can only specify the default behavior of a control.
Templates
  1. Templates   Used only those elements that inherit from the Control class in the System.Windows.Control namespace.
  2. By using  Templates u can modify the structure of the Control to which the Template is applied.
  3. Templates      Values can’t be overridden by the values that are set on the control itself when it is drawn on the artboard .But , using Template Binding the property’s  value can set of a template according to the values of a properties of the control when it is drawn on the artboard.
  4. When u  Modify with Template u can access to more parts of control then styles.
  5. By  using   Trigger u can specify the behavior of any new & existing parts in a Template.


Difference between UserControl & Custom Control

UserControls
  1. UserControl is easier to create.
  2. UserControl defines its User Interface in the plain xaml file.
  3. User control also can be added in your toolbox. It is a tightly coupled control with respect to your code .
  4. Once u use UserControl in UI it is fixed can’t be changed in ur referenced projects.
  5. UserControl derives from System.Windows.Controls.UserControl.
  6. UserControls can’t be, themeable , or skinnable(only child controls of usercontrol are skinnable).
  7. UserControl is a set of Controls
CustomControl
  1. CustomControl   Is  harder to create
  2. CustomControl     defines it's User Interface in ResourceDictionary generally called it generic.xaml
  3. CustomControl     Full Toolbbox Support .It is a loosely coupled control with respect to your code.
  4. CustomControl  Gives much more flexibility & u are freedom to use(can be changed) it in ur any referenced Projects.
  5. CustomControl    Derives from System.Windows.Controls.Control Class ,
  6. CustomControl    Canbe Themeable,Skinnable
  7. CustomControl  generally  Defines in a single control

A Custom Control in Silverlight 5

In silverlight project I have seen using custom control are vast.every control should be custom according to requirement.I have known lot of things on that.But in searching in internet there also various site regarding on that . MSDN is one of them good resources and others site are also available describing the CustomControl good enough. Whatever I have seen Custom Controls are like Textboxes, Text Blocks, Combo boxes, DatePickes etc . Now it is a little bit confusing that when Microsoft is providing So many controls & u can easily get it in ur ToolBox of ur VisualStudio2010 Silverlight Projects. So what is the meaning of CustomControls & I have also written the example of customcontrols like TextBoxes, DatePicker….. Well , we are going little deep of its basics.

What is CustomControl?

Generally speaking a CustomControl is a loosly coupled control usually defined in a class, which derives from  an existing control and extends it functionality in different way. Though CustomControl  are defined within in a Class But , the visual effects (I mean the UI of custom Control) generally defined in Resource Dictionary inside the resource file . This makes it little complex. But, u have a freedom to make our desired control as we want.

What are the benefits of CustomControl?

CustomControls are reusable controls. Once u creates a custom Control u can simply use it in different projects by simply add the assembly in the projects. Yes , in our Visual Studio toolbox  what we do Simply Drag & drop our controls from this and use this as per requirement. But generally u can’t able to see ur newly make customcontrol in toolbox for that there need to do some additional steps . I’m skipping this at this moment . Not only CustomControl is a reusable controls but also they can be skinnable,themable in any projects.
One thing also is that we make our CustomControl because of sometimes ur Silverlight common control doesn’t cover our specific requirements to apply in Projects.
The buttons, Textboxes, Comboxes …. etc even usercontrol are also customcontrol. Usually a CustomControl is inherit from System.Windows.Controls.Control or  System.Windows.Controls.ItemsControl or System.Windows.Controls.ContentControl etc.
  • Controls : Represents the base class for UI elements that use a ControlTemplate to define their appearance.
  •  ItemsControl : Represents a control that can be used to present a collection of items.
  •  ContentControl : Represents a control with a single piece of content. Controls such as Button, CheckBox, and ScrollViewer directly or indirectly inherit from this class.

When to use CustomControl  ?

Now this is good idea when should I use CustomControl . I also write some description on it but  have  a look for clear idea.
  •  Use CustomControl   when you think that ur basic controls doesn’t provide much more functionality as u want , then pl make a customcontrol for urself.
  •  When  u want to apply theme to ur control ,use CustomControl  .
  • Suppose u have more than two projects in ur Silverlight Appliclications & using same components so it is better idea to make them a CustomControl  instead of  combinging or grouping them in UI and write code for multiple times .
  •  Use CustomControl   when u think to make a completely new control or a specific version of a control.
OK…I hope this gives a basic idea where & when to use CustomControl but may be there some specific requirements to u to make a Custom Control.
For understanding other flexibility of CustomControl u need to know about Usercontrol. And basic difference between CustomControl  & UserControls . Let’s see….

What is a user Control?

Use UserControl when u needs a fixed content control which will encapsulate related existing control and provides its own logics.  Also when you separate ur basic functionality of UI page(view page ) in to some smaller , manageable pieces of logics with reusability then use User Control. In Silverlight , generally we put the User Control as a root of element in application.
Now

Download




Tuesday, January 29, 2013

Customizing Silverlight 5 DataGrid Headers


We’re currently working on a client application that captures time sheet information and needed the ability to completely customize the look and feel of DataGrid headers.  Fortunately, that’s fairly straightforward to do in Silverlight 3 (or Silverlight 2 for that matter).  Nearly all of the columns being used are DataGridTemplateColumn types (although that’s not required to customize headers) and changing the header is accomplished by using the HeaderStyle property as shown next:
<data:DataGridTemplateColumn Header="Tue" HeaderStyle="{StaticResource TimeSheetDayHeaderStyle}">
    <data:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBox Text="{Binding TuesdayQuantity}" Style="{StaticResource TimeSheetTextBoxStyle}"/>
                <Rectangle Fill="#FFC9CACA" VerticalAlignment="Stretch" Width="1" />
                <TextBox Text="{Binding TuesdayHours}" Margin="2,0,0,0" Style="{StaticResource TimeSheetTextBoxStyle}"/>
            </StackPanel>
        </DataTemplate>
    </data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
see the link http://weblogs.asp.net/dwahlin/archive/2009/06/11/customizing-silverlight-3-datagrid-headers.aspx

Cell merge in datagird

Problem:
I would like to create datagrid that has nested columns (please look at attached image). Or if possible embed grid into cell. My objects have many different informations, and based on object type I would like to add additional info in my cell (nested Column in the image), that is divided by columns. Is it possible in silverlight ?
Solution:
If it's just displaying values from multiple columns in one column it is best to do this by using a 
DataGridTemplateColumn:

<sdk:DataGridTemplateColumn Header="Merged Cols">
    <sdk:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel>
                <sdk:DataGrid Name="dataGrid2" AutoGenerateColumns="True" HeadersVisibility="None"/>
            </StackPanel>
        </DataTemplate>
    </sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
You could also do this through a converter if you want to use the DataGridTextColumn. As a Silverlight converter only supports one value you'd need to send the entire row.
The column definition of the DataGrid would contain
<sdk:DataGridTextColumn Binding={Binding Converter={StaticResource MergedCols}} />
You'd need to add the MergedCols converter to your solution and to your resource collection.
<UserControl.Resources>
    <myConverters:MergedColsConverter x:Key="MergedCols" />

Wednesday, January 23, 2013

Using the AutoCompleteBox

see the link
http://www.silverlightshow.net/items/Using-the-AutoCompleteBox.aspx
http://www.codeproject.com/Articles/55993/AutoComplete-ComboBox-for-Silverlight

Auto Select Text in TextBox

see the link
http://dnchannel.blogspot.com/search/label/xaml

Some Drawback of Silverlight Control


  1. Silverlight text box does not support mouse click.
  2. Silverlight Child Window does not support global style in app
  3. Silverlight window always create new environment.
  4. Silverlight Content Control does not support sizing.
  5. RIA service can not support method overloading.
  6. there is a sensible level of deception and frustration. Missing features, cut-off or half-backed functionality, leaking resources and a failed promise to offer a viable way to develop cross-platform applications. And the worst of all, I think we’ve lost time working around various limitations of Silverlight in order to get it working properly and comply with our requirements (somewhere between 10 to 15 %%).

A Simple Pattern for Creating Re-useable UserControls in WPF / Silverlight


see the link
http://www.codeproject.com/Articles/325911/A-Simple-Pattern-for-Creating-Re-useable-UserContr

Resource File Add From Other Project


I am keen to interest to develop a Silverlight application with mvvm pattern but have some drawback to have to implement.
To have to develop mvvm pattern application i have needed a resource file add into my Silverlight project from another project.

You may have understood my problem. Here i am discussing solution of my problem with appropriate source code step by step.

First Step:
                Open your Silverlight project
Second Step:
                Open the App.xaml.cs file
Third Step:
                Copy the source code
                ResourceDictionary p = new ResourceDictionary();
                p.Source = new Uri("/AnotherProject;component/Themes/generic.xaml", UriKind.Relative);
               this.Resources.MergedDictionaries.Add(p);
Fourth Step:
                Paste the source code into app constructor that like as
         public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
            ResourceDictionary p = new ResourceDictionary();
            p.Source = new Uri("/AnotherProject;component/Themes/generic.xaml", UriKind.Relative);
            this.Resources.MergedDictionaries.Add(p);
        }

Tuesday, January 22, 2013

Silverlight Shadow Example

see the link
http://www.nokola.com/

Silverlight 4 Binding ContentPresenter Content


In WPF and Silverlight there is an element called ContentPresenter, that is often used inside control templates, as well as inside the root application markup. The concept of ContentPresenter is quite simple – it is a placeholder for any XAML content and it can be used to insert content at runtime.
What I personally find it useful for is dynamic user interface, where there is no need to define a static UI structure at design time, but at runtime there should be some components that are either defined in the application XAML or in an external resource.
A content presenter is used via the ContentPresenter element: <ContentPresenter></ContentPresenter>. The content inside this element can be partially (or completely, although its value is lost in this case) defined inside the <ContentPresenter.Content></ContentPresenter.Content> element.
If you consider using the ContentPresenter element by defining the content from scratch, there is no need to include the Content element in the base XAML – it cannot be empty and running it so will cause an exception to be thrown. Once the content is set at runtime, the proper tag will be added automatically.
Let’s take a look at an example
<Grid>
        <ContentPresenter Name="MyContent">
           
        </ContentPresenter>
    </Grid>




Monday, January 21, 2013

Content Controls in Silverlight


Once you get in touch with the Silverlight Templated controls it became evident that there are three kind of controls you can put in the XAML. Given that the structure of the page is a hierarchical tree - for this reason is is commonly called Visual Tree - you can expand this paradigm to understand the three types of controls.
  • "Leaf" controls  are classes inherited from Control and they terminate the hierarchy because nothing can be inserted into them
  • "Content" controls are inherited from the ContentControl class. These controls can host other elements inside of them. They are nodes in the hierarchy
  • "Items" controls are usually inherited from ItemsControl and they can contain multiple instances of child controls so they are also a particular case of nodes with many branches starting from it.
The boundary between one kind and the other is not always immediately evident when you use a control. As an example, if you consider the Button control at the first sight is may seems a leaf control but instead it is a Content control and thanks to this you can have button that hosts images and texts and not only a label.
When you start creating a templated control the choice of the class from which inheriting is really important and you have to make the choice carefully because this choice can impact the effectiveness and reusability of the control. Many times the choice of inheriting from Control is good, but you have always to try to give a chance to the ContentControl, reasoning about the final structure you want to achieve. Content control can often give an additional gear to your work paying an often low price in when you first create the control layout.

Creating a ContentControl from scratch

Sunday, January 20, 2013

Custom DataPager With PageSize DropDown in Silverlight

In real time application huge data can be handle into grid of one page. then we can use data pager according to page size which offers navigation such example you can downloadable


http://www.codeproject.com/Articles/292858/Custom-DataPager-With-PageSize-DropDown-in-Silverl



Thursday, January 17, 2013

5 Questions You Should Never Ask in a Job Interview

Here are 5 questions that can make a bad impression on your interviewer, scuttling your chances for getting the job. 

1. "When will I be promoted?:This is one of the most common questions that applicants come up with, and it should be avoided, says Rebecca Woods, Vice President of Human Resources at Doherty Employer Services in Minneapolis. "It's inappropriate because it puts the cart before the horse."  Instead of asking when the promotion will occur, Woods says a better approach is to ask what you would need to do to get a promotion. 

2. "What's the salary for this position?"Asking about salary and benefits in the first interview "always turns me off," says Norma Beasant, founder of Talento Human Resources Consulting and an HR consultant at the University of Minnesota. "I'm always disappointed when they ask this, especially in the first interview." Beasant says the first interview is more about selling yourself to the interviewer, and that questions about salary and benefits should really wait until a later interview. 

3. "When can I expect a raise?"Talking about compensation can be difficult, but asking about raises is not the way to go about it, Woods says. So many companies have frozen salaries and raises that it makes more sense to ask about the process to follow or what can be done to work up to higher compensation level. Talking about "expecting" a raise, Woods says, "shows a person is out of touch with reality."
 
4. "What sort of flextime options do you have?"This kind of question can make it sound like you're interested in getting out of the office as much as possible. "When I hear this question, I'm wondering, are you interested in the job?" Beasant says. Many companies have many options for scheduling, but asking about it in the first interview is "not appropriate," Beasant says.
 
5. Any question that shows you haven't been listening. Woods said she interviewed an applicant for a position that was 60 miles from the person's home. Woods told the applicant that the company was flexible about many things, but it did not offer telecommuting. "At the end of the interview, she asked if she would be able to work from home," Woods says. "Was she even listening? So some 'bad questions' can be more situational to the interview itself." 

With the economy the way it is, employers are much more choosy and picky, Beasant says. Knowing the questions to avoid in an interview can help you stand out -- in a good way.

Wednesday, January 16, 2013

Some important link in silverlight learn


---------------------------------------Books-----------------------------------------
http://www.free-eboooks-download.org
http://books.google.com.bd/books?id=1MsETFPD3I0C&printsec=frontcover#v=onepage&q&f=false
----------------------------------------Started---------------------------------------
http://code.msdn.microsoft.com/Getting-Started-WCF-RIA-1469cbe2
http://www.componentone.com/SuperProducts/StudioSilverlight/Demos/?utm_source=silverlight.net&utm_medium=microtext%2Bros&utm_content=samples&utm_campaign=studio%2Bfor%2Bsilverlight
http://mfelicio.com/
http://weblogs.asp.net/dwahlin/archive/2010/05/10/integrating-html-into-silverlight-applications.aspx
http://projectsilverlight.blogspot.com/
http://wsinsiders.com/2010/01/29/silverlight-tutorials-for-beginners/
http://compositewpf.codeplex.com/
http://openlightgroup.net/Blog/tabid/58/EntryId/89/Silverlight-View-Model-Style-An-Overly-Simplified-Explanation.aspx
http://www.codeproject.com/Articles/90071/RIATasks-A-Simple-Silverlight-CRUD-Example-using-V
http://www.codeproject.com/Articles/69004/Silverlight-File-Manager
http://www.codeproject.com/Articles/72032/Silverlight-4-Video-Player
http://www.gleblanc.eu/Blog/post/Menus-Part-I.aspx

http://samples.msdn.microsoft.com/Silverlight/SampleBrowser/index.htm#/?sref=transforms_ovw_interactive_transforms
http://archive.msdn.microsoft.com/silverlightsdk
https://skydrive.live.com/?cid=2c5f5b0560e374cb&id=2C5F5B0560E374CB%21547
http://mariaevert.dk/thesis/?m=201007
https://skydrive.live.com/?cid=9fdb2a0b191b39e2&id=9FDB2A0B191B39E2%21136
http://msdn.microsoft.com/en-us/library/ff921074(v=pandp.40).aspx
https://skydrive.live.com/?cid=B692C2CBAD70A05C&id=B692C2CBAD70A05C%21127&sc=documents
--Button Style And Templete--
http://msdn.microsoft.com/en-us/library/cc278075(v=vs.95).aspx

http://www.hanselman.com/blog/TheWeeklySourceCode36PDCBabySmashAndSilverlightCharting.aspx
http://www.michielpost.nl/


-----------------------very very importnt-----------
http://asimsajjad.blogspot.com/search/label/MVVM
http://silverlightmvvmblogs.blogspot.com/2010/09/building-silverlight-application-using.html
http://blog.micic.ch/net/easy-mvvm-example-with-inotifypropertychanged-and-inotifydataerrorinfo
http://www.4shared.com/file/ALbjHxfS/Laboratory.html
http://www.silverlightshow.net/items/WCF-RIA-Services-Part-4-Integrating-with-the-Model-View-ViewModel-Pattern.aspx
http://weblogs.asp.net/scottgu/archive/2010/04/22/silverlight-4-training-kit.aspx
http://silverlight.adefwebserver.com/
http://www.c-sharpcorner.com/tags/DataGrid.LoadingRow-Event-in-silverlight
http://www.dotnetfunda.com/articles/article1180-asynchronous-method-using-task.aspx
http://www.silverlightshow.net/items/Using-the-AutoCompleteBox.aspx
http://geekswithblogs.net/lbugnion/archive/2010/05/19/handling-datagrid.selecteditems-in-an-mvvm-friendly-manner.aspx
http://www.codeproject.com/Articles/252958/Access-Controls-in-ViewModel-using-Attached-Proper
http://msdn.microsoft.com/en-us/library/ee707373(v=VS.91).aspx
--Custom Control Link
http://www.dotnetfunda.com/articles/article1529-a-custom-control-in-silverlight-4.aspx

-------------------------------Performance measurement---------------------------------------------
http://msdn.microsoft.com/en-us/library/cc189071(v=vs.95).aspx
http://www.silverlightshow.net/items/Caching-of-in-and-around-your-Silverlight-application-part-2.aspx
http://blog.falafel.com/blogs/11-12-02/Faster_Silverlight_XAP_Downloads_with_Application_Library_Caching
http://www.codeproject.com/Articles/180642/Performance-tips-for-RIA-Service-with-Silverlight

-------------------------Printing---------------------------------------------------
http://www.davidpoll.com/2010/04/16/making-printing-easier-in-silverlight-4/
http://www.davidpoll.com/downloads-and-samples/#SLaB
http://www.silverlightshow.net/items/A-look-at-the-Printing-API-in-Silverlight-4.aspx
http://www.silverlightshow.net/items/Advanced-printing-in-Silverlight-4.aspx

----------------------Codeing link--------------------------------
http://www.slideshare.net/msdnbelux/243-room10-kevindockx
https://skydrive.live.com/?cid=b692c2cbad70a05c&sc=documents&uc=1&id=B692C2CBAD70A05C%21127
https://github.com/posabsolute/jQuery-printPage-plugin/blob/master/jquery-1.4.4.min.js
https://skydrive.live.com/?cid=2c5f5b0560e374cb&id=2C5F5B0560E374CB%21213
https://skydrive.live.com/?cid=289eaf995528b9fd&id=289EAF995528B9FD%21422
https://skydrive.live.com/?cid=d34608bce9688fba&sc=documents&id=D34608BCE9688FBA%21343
https://skydrive.live.com/?cid=1bf46693be07cfa6&sc=documents&id=1BF46693BE07CFA6%21223
https://skydrive.live.com/?cid=71b364b59919d1e8&id=71B364B59919D1E8%21232
https://skydrive.live.com/?cid=d2868c4e2b15623f&id=D2868C4E2B15623F%21307

Column Header CheckBox of Data Grid

Add reference

xmlns:dataprimitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"

Add Column into silverlight data grid


<sdk:DataGrid.Columns>
                    <sdk:DataGridTemplateColumn Width="20">
                        <sdk:DataGridTemplateColumn.HeaderStyle  >
                            <Style TargetType = "dataprimitives:DataGridColumnHeader">
                                <Setter Property="Template">
                                    <Setter.Value>
                                        <ControlTemplate>
                                            <Grid>
                                                <Grid.ColumnDefinitions>
                                                    <ColumnDefinition></ColumnDefinition>
                                                </Grid.ColumnDefinitions>
                                                <CheckBox x:Name="chkAll" IsChecked="{Binding Path=VMVPO.IsSelectAll, Mode=TwoWay}" Grid.Column="0">
                                                    <i:Interaction.Triggers>
                                                        <i:EventTrigger EventName="Click">
                                                            <i:InvokeCommandAction Command="{Binding SelectAll, Source={StaticResource dd}}" CommandParameter="{Binding ElementName=chkAll}" />
                                                        </i:EventTrigger>
                                                    </i:Interaction.Triggers>
                                                </CheckBox>
                                            </Grid>
                                        </ControlTemplate>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </sdk:DataGridTemplateColumn.HeaderStyle>
                        <sdk:DataGridTemplateColumn.CellTemplate  >
                            <DataTemplate>
                                <CheckBox Name="chkSelect" IsChecked="{Binding Path=IsEnabled, Mode=TwoWay}"/>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>

Tuesday, January 15, 2013

Framework Element Enter Key Press Event

Add two class your project

public class TextBoxEnterKeyTrigger : TriggerBase<UIElement>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            TextBox textBox = this.AssociatedObject as TextBox;

            if (textBox != null)
            {
                this.AssociatedObject.KeyUp += new System.Windows.Input.KeyEventHandler(AssociatedObject_KeyUp);
            }
            else
            {
                throw new InvalidOperationException("This behavior only works with TextBoxes");
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.KeyUp -= new KeyEventHandler(AssociatedObject_KeyUp);
        }

        private void AssociatedObject_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                TextBox textBox = AssociatedObject as TextBox;

                //This checks for an mvvm style binding and updates the source before invoking the actions.
                BindingExpression expression = textBox.GetBindingExpression(TextBox.TextProperty);
                if (expression != null)
                    expression.UpdateSource();

                InvokeActions(textBox.Text);
            }
        }
    }

    public class ExecuteCommandAction : TriggerAction<DependencyObject>
    {
        #region Properties

        public ICommand Command
        {
            get { return (ICommand)base.GetValue(CommandProperty); }
            set { base.SetValue(CommandProperty, value); }
        }

        public static ICommand GetCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        // We use a DependencyProperty so we can bind commands directly rather
        // than have to use reflection info to find them
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register("Command", typeof(ICommand), typeof(ExecuteCommandAction), null);
        #endregion Properties

        protected override void Invoke(object parameter)
        {
            ICommand command = Command ?? GetCommand(AssociatedObject);
            if (command != null && command.CanExecute(parameter))
            {
                command.Execute(parameter);
            }
        }
    }

and used this way


<TextBox
                                  Text="{Binding Path=text, Mode=TwoWay,ValidatesOnExceptions=True, NotifyOnValidationError=True}">
                        <i:Interaction.Triggers>
                            <lib:TextBoxEnterKeyTrigger>
                                <lib:ExecuteCommandAction Command="{Binding Path=Command,Mode=TwoWay}"/>
                            </lib:TextBoxEnterKeyTrigger>
                        </i:Interaction.Triggers>
                    </TextBox>



Monday, January 14, 2013

Data grid selected item command in mvvm

http://geekswithblogs.net/lbugnion/archive/2010/05/19/handling-datagrid.selecteditems-in-an-mvvm-friendly-manner.aspx

http://msmvps.com/blogs/deborahk/archive/2011/02/13/silverlight-mvvm-commanding-ii.aspx

http://asimsajjad.blogspot.com/2011/07/get-selecteditems-from-datagrid-using.html

Synchronously Retrieving Data with WCF RIA Services

http://blog.falafel.com/Blogs/scott-frolich/2010/08/12/Synchronously_Retrieving_Data_with_WCF_RIA_Services

Creating a RIA Services Solution With VS 2012


To set up a RIA Services solution

  1. Create a new RIA Services project in Visual Studio 2012 by selecting FileNew, and then Project.
    The New Project dialog box appears.
  2. Select the Silverlight Application template from Silverlight group of the Installed Templates and name the new project RIAServicesExample.
    Click OK.
    1. The New Silverlight Application dialog box appears.
    2. Select the Enable WCF RIA Services check box near the bottom of the dialog box. Checking this box creates a RIA Services link between the client project and the server project.
      3. Click OK to create the solution.
      The solution contains two projects: a client project and a server project. The client project is named RIAServicesExample and it contains the Silverlight code that you use to create the presentation tier. The server project is named RIAServicesExample.Web and it contains the middle-tier code.
      4. Add Edm to your project by graphical interface and set the name default

      5. Generate your entity model
      6.Choose Connection string by this way
      7. Set Data Base Name
      8. Select Sql Server
       9. Choose Radio button yes and press next button
       9. Select Data Base Table or Sp
       10.Delete the two “.tt” generated files in the entity model
      11.Open your entity model in the designer and change Code Generation Strategy from "None" to "Default"
      12.Rebuild the project and Now you can add a new Domain Service
       13.Check Like as image

      14.Rebuild your solution and add code to MainPage.xaml page

       15.Add the Following code into MainPage.cs Page
       16.Build your Solution and Run,now you can see data look like as
      17.Thank you




Thursday, January 10, 2013

Finish all service load complete check

Add the method below

when All Loading Complete then this method fire and busy indicator is inactive
        protected virtual void OnLoadingCompleted(EventArgs e)
        {
            --load complete
        }

        locker object for no call other
        private readonly object _locker = new object();
        private int _loadingCompletedCount;

        number of loading
        private const int TotalLoading = 13;

        Check how many loading are complete
        public void IsLoadingCompleted()
        {
            lock (_locker)
                ++_loadingCompletedCount;
            if (_loadingCompletedCount >= TotalLoading)
                OnLoadingCompleted(new EventArgs());
        }

and call IsLoadingCompleted() method into every load complte

Async chain of service calls in Silverlight


A colleague of mine asked me how to chain service calls in a Silverlight async model.
Lets say you have these two operations:
string GetId()
void Calculate(string id)
And you must call GetId first and then use the result of that operation to call the Calculate operation.
The solution is pretty simple. We can use our old friend; the AutoResetEvent class. Luckly this exist in Silverlight as well.
First we put the task on the ThreadPool so we don’t block the UI Thread:
private void Button_Click(object sender, RoutedEventArgs e)
{
    ThreadPool.QueueUserWorkItem(StartWork);
}
And here is the StartWork method:
public void StartWork(object state)
{
    var dataService = new DataServiceClient();
    var personService = new PersonServiceClient();

           string id = string.Empty;
           dataService.GetIdCompleted += (s, e) =>
           {
               id = e.Result;

               //signal the event, so the thread can continue
               autoResetEvent.Set();
           };

           //call GetIdAsync
           dataService.GetIdAsync();

           //pause the thread
           autoResetEvent.WaitOne();

           //call CalculateAsync with the id
           personService.CalculateAsync(id);
}