How do I prism 2 videos for Silverlight

Published 28.02.2009 08:15 AM by Admin in Silverlight

Bob and Erwin put together a series of videos that tell how to modular Silverlight Application. For more information see Bobs blog.

 

Creating a solution and adding a module (10 minutes)


Composing views (10 minutes)
 

Implementing a view and using services (22 minutes)
 

Communicating between views (24 minutes)

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Last week I have been started to read about full duplex wcf and his implementation in silverlight applications.I have read tons of articles on MSDN and tons of blog and forum posts.

Recently I have found solution for chat application on this blog http://silverbling.blogspot.com/2009/01/using-pollingduplexhttpbinding-for.html 

so I have little modified that application but it is basically same application.This application is based on this blog post of Dan Wahlin :

http://weblogs.asp.net/dwahlin/archive/2008/06/16/pushing-data-to-a-silverlight-client-with-wcf-duplex-service-part-i.aspx

Everything that you need to know about building wcf full duplex application for silverlight you can find on msdn :

http://msdn.microsoft.com/en-us/library/cc645027(VS.95).aspx

and for accessing wcf duplex from silverlight client:

http://msdn.microsoft.com/en-us/library/cc645028(VS.95).aspx 

This application is also based on same articles above.This is simple chat application that has no chat rooms.Same concept you can use for developing multiplayer online silverlight games.

If you want to modify this application to add rooms you can look some useful pattern for that  List-Based Publish-Subscribe  :

http://msdn.microsoft.com/en-us/library/ms752254.aspx

What I have get when I have finished project looks like this :

Ielook1

Only thing that you need to do to make this project work for you is to change url of your wcf web service in page.xaml.cs .

this.pusher = new PushDataReceiver(

                this.processor,

                "http://localhost.:5433/SilverlightChatDuplexService.svc",

                "Silverlight/ISilverlightChatDuplexService/InitiateDuplex",    // The Wcf function or action.

                "");

 

Demo project : SilverlightChatSource

 

 

Currently rated 3.5 by 2 people

  • Currently 3.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

In this  article I will explain how to implement MVVM pattern in Silverlight.

I was very overjoyed when I was reading my friends article on Codeproject about MVVM pattern in WPF .

You can check this article by Miroslav Popovic on http://www.codeproject.com/KB/WPF/FirefoxLikeSearchWithMVVM.aspx

I have decided to try implement same pattern in Silverlight .After reading and researching about MVVM pattern and his implementation in Silverlight I have found that most used method for implementing something close to MVVM in Silverlight is done by using SLEextension libraries.

SLEextension libraries you can found on Codeplex at this adress : http://www.codeplex.com/SLExtensions

When we talk about MVVM pattern and his implementation we must mention concept of attached behaviors and what is main purpose of MVVM pattern.

The Attached Behavior pattern encapsulates "behavior" (usually user interactivity) into a class outside the visual heirarchy and allows it to be applied to a visual element by setting an attached property and hooking various events on the visual element.(definition by John Gossman)

Main concept of MVVM pattern is to shrink or completly remove logic from the presentation.More about these patterns you can read from links below.

There are many ways to implement attached behavior in Silverlight.You can use SilverlightFX libraries from Nikhil Kothari or something else but most easiest way to do this is to use SLEextensions library.

I will show you now how to implement this on small exemple project.I have created form with button, textbox and  datagrid control.Main purspose of this form is when you enter searh text and press search button grid is populated with filtered data.

Picture1

First we need to add reference to SLExtensions.dll.After that we need to create static class Commands where we need to put all our methods.We now create our method GetData.Whery important thing is to create static void Initialize to ensure later that static fields are initialized.

This class looks like this :

public static class Commands

    {

        static Commands()

        {

            GetData = new Command("GetData");

        }

 

        public static Command GetData

        {

            get;

            private set;

        }

        ///

        /// Ensure static fields are initialized

        ///

        public static void Initialize()

        {

        }

    }

After that we need to create base class for all ViewModels.It looks like this :

public abstract class ViewModel : INotifyPropertyChanged

    {

        public event PropertyChangedEventHandler PropertyChanged;

 

        protected virtual void OnPropertyChanged(string propertyName)

        {

            if (PropertyChanged != null)

                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

        }

    }

and PersonViewModel class that has some important things.

In constructor PersonViewModel class we set what method will be responsible when GetData method executes.In setter or public property List we must set OnPropertyChanged method to occcur.

public class PersonViewModel:ViewModel

    {

        private List<Person> list;

        public string City { get; set; }

        public List<Person> List

        {

            get { return list; }

            set

            {

                list = value;

                OnPropertyChanged("List");

            }

        }

 

        public PersonViewModel(string CityP)

        {     

           City = CityP;

           Commands.GetData.Executed+=new System.EventHandler<ExecutedEventArgs>(GetData_Executed);

        }

 

        void GetData_Executed(object sender, ExecutedEventArgs e)

        {

            List = Model.Person.GetPeople();

            var query = from c in List

                        where c.City.ToLower().StartsWith(City.ToLower())

                        select c;

            List=query.ToList();

        }

 

    }

In xaml file we need to add reference to

xmlns:Input="clr-namespace:SLExtensions.Input;assembly=SLExtensions"

and set what method will be attached to button control.

Input:CommandService.Command="GetData"  
Input:CommandService.CommandParameter="{Binding}"

After that only two things more we must do.First we need to ensure that before proccesing xaml file static commands are created,and we need to on button click event pass PersonViewModel to Datacontext element to populate dataGrid control.

        public Page()

        {

            // Ensure static commands are created before xaml is processed

            Commands.Initialize();

            InitializeComponent();         

        }

 

        private void btnOK_Click(object sender, RoutedEventArgs e)

        {

            DataContext = new PersonViewModel(txtSearch.Text);

        }

I hope this will be good starting point for you to try to implement this pattern in your own projects. I think that reasons for implementing this pattern are obvious (testibility, separation from presentation layer…) but debbuging  is very big problem for everybody try to use this pattern in real Silverlight application.

Demo project: SilverlightMVVM.rar

 

Source :

Attached behavior pattern :

http://blogs.msdn.com/johngossman/archive/2008/05/07/the-attached-behavior-pattern.aspx

http://www.nikhilk.net/Silverlight-Behaviors.aspx

http://blogs.southworks.net/jdominguez/2008/08/icommand-for-silverlight-with-attached-behaviors/

MVVM pattern :

http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx

http://blogs.msdn.com/dancre/archive/2006/10/11/datamodel-view-viewmodel-pattern-series.aspx

http://www.nikhilk.net/Silverlight-ViewModel-Pattern.aspx

http://tozon.info/blog/post/2009/01/20/Silverlight-TreeView-MVVM-and-editing-1.aspx

http://mark-dot-net.blogspot.com/2008/11/model-view-view-model-mvvm-in.html

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Styling silverlight datagrid control

Published 08.02.2009 11:12 AM by Admin in C# | Silverlight

This article will explain you how to  modify default silverlight datagrid control look.

In this example I have created new silverlight application project and add datagrid control in xaml file.I have also created small class called Person to populate test data.

 public class Person

        {

            public int ID { get; set; }

            public string FirstName { get; set; }

            public string LastName { get; set; }

            public string City { get; set; }

        }

After I've set ItemsSource property of datagrid control to list of persons I have recived this error :

       Message: System.MethodAccessException: Person.get_ID()

       at System.Reflection.MethodBase.PerformSecurityCheck(Object obj, RuntimeMethodHandle method, IntPtr parent, UInt32 invocationFlags)

       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)

       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)

       at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)

           at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)

Resolution is to set my class Person to be public class.

Silverlight DataGrid control has default style for DataGrid,DataGridColumnHeader,DataGridRowHeader,DataGridRow,DataGridCell... We can examine this styles, modify them and create our own styles from this styles.

To examine this styles there is great tool called SilverlightDefaultStyleBrowser by Delay

http://blogs.msdn.com/delay/archive/2008/03/22/improved-access-to-silverlight-2-s-generic-xaml-resources-silverlightdefaultstylebrowser-available-via-clickonce.aspx

After I have modify some default styles I have got this look of silverlight datagrid :


First we need to add some new namespaces into xaml

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

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

        xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"

We must put all styles into

 <Grid.Resources>

of xaml file.Now I will explain some properties of DataGridStyle.All these properties we can also set directly into dataGrid control or we can create new style that we can easily reuse later in project.

<Style  x:Key="newDataGridStyle"  TargetType="data:DataGrid">
       <Setter Property="RowBackground" Value="#CFEEDE" />
       <Setter Property="AlternatingRowBackground" >
             <Setter.Value>
                  <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                  <GradientStop Color="#FFA3AEB9" Offset="0"/>
                  <GradientStop Color="#FF8399A9" Offset="0.375"/>
                  <GradientStop Color="#FF718597" Offset="0.375"/>
                  <GradientStop Color="#FF617584" Offset="1"/>
                  </LinearGradientBrush>
              </Setter.Value>
        </Setter>
        <Setter Property="Background" Value="#3E88B4" />
        <Setter Property="HeadersVisibility" Value="Column" />
        <Setter Property="HorizontalScrollBarVisibility" Value="Auto" />
        <Setter Property="VerticalScrollBarVisibility" Value="Auto" />
        <Setter Property="SelectionMode" Value="Single" />
        <Setter Property="CanUserReorderColumns" Value="False" />
        <Setter Property="CanUserResizeColumns" Value="False" />
        <Setter Property="CanUserSortColumns" Value="True" />
        <Setter Property="AutoGenerateColumns" Value="True" />
        <Setter Property="RowDetailsVisibilityMode" Value="VisibleWhenSelected" />
        <Setter Property="BorderBrush">
             <Setter.Value>
                 <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                 <GradientStop Color="#FFA3AEB9" Offset="0"/>
                 <GradientStop Color="#FF8399A9" Offset="0.375"/>
                 <GradientStop Color="#FF718597" Offset="0.375"/>
                 <GradientStop Color="#FF617584" Offset="1"/>
                 </LinearGradientBrush>
             </Setter.Value>
         </Setter>
</Style >

As you can see on picture of dataGrid RowBackground property represent color of each row and AlternatingRowBackground property represent color every second row.If we set these two property to be equals all rows in grid will be same style.I have put code from borderBrush into AlternatingRowBackground property to get linearGradientBrush efect on every second row. SelectionMode property determine will multiselect support will be enabled or disabled.It has two values single and extended.

Very imortant is to set Grid.Resources above DataGrid control becouse if we try to set style of dataGrid and resources are bellow, dataGrid can't see those resources.After we have modified default style and put that style in  Grid.Resources we just add this code to apply style to dataGrid:

Style="{StaticResource newDataGridStyle}"

where newDataGridStyle is name of Style that we have define using x:Key .

Also many people ask how to change background color of DataGridHeader.It is easy to accomplish by modifing default DataGridColumnHeader style. We just need to change

  < vsm:VisualState x:Name="Normal" >

and put some code for getting efect like on picture above:

<vsm:VisualState x:Name="Normal" >
     <Storyboard>
        <ColorAnimationUsingKeyFrames BeginTime="0" Duration="0" Storyboard.TargetName="BackgroundRectangle" 
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
             <SplineColorKeyFrame KeyTime="0" Value="#0A2752"/>
        </ColorAnimationUsingKeyFrames>
        <ColorAnimationUsingKeyFrames BeginTime="0" Duration="0" Storyboard.TargetName="BackgroundGradient" 
Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[3].(GradientStop.Color)">
             <SplineColorKeyFrame KeyTime="0" Value="#366AB5"/>
        </ColorAnimationUsingKeyFrames>
        <ColorAnimationUsingKeyFrames BeginTime="0" Duration="0" Storyboard.TargetName="BackgroundGradient" 
Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[2].(GradientStop.Color)">
             <SplineColorKeyFrame KeyTime="0" Value="#ACC4E7"/>
         </ColorAnimationUsingKeyFrames>
         <ColorAnimationUsingKeyFrames BeginTime="0" Duration="0" Storyboard.TargetName="BackgroundGradient" 
Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)">
             <SplineColorKeyFrame KeyTime="0" Value="#ACC4E7"/>
         </ColorAnimationUsingKeyFrames>
      </Storyboard>
</vsm:VisualState>

I hope that this article will be good starting point for you to create your own styles for dataGrid control.

 

Demo project : DataGridStylesAndTemplates.rar (955.22 kb)

 

Source :

http://msdn.microsoft.com/en-us/library/cc278066(vs.95).aspx

http://msdn.microsoft.com/en-us/library/cc189093(VS.95).aspx

 

Currently rated 4.0 by 2 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Silverlight supports fullscreen mode

Published 05.02.2009 04:32 PM by Admin in C# | Silverlight

Silverlight 2 has build in support  for fullscreen mode.This feature can be very interested for building same online game solution or some cool video players or ...When we enter to this fullscreen mode everything is hidden including browser frame.

We can also resize our application to fit new changed screen size using two events in

Application.Current.Host.Content class.This class is located in C:\Program Files\Microsoft SDKs\Silverlight\v2.0\Reference Assemblies\System.Windows.dll and it looks like this :

        public sealed class Content

        {

            // Fields

 

            private EventHandler FullScreenChanged;

            private EventHandler Resized;

 

            // Events

 

            public event EventHandler FullScreenChanged;

            public event EventHandler Resized;

 

            // Methods

 

            public Content();

 

            internal void FireFullScreenChanged(object sender, EventArgs args);

            internal void FireResized(object sender, EventArgs args);

 

            // Properties

 

            public double ActualHeight { get; }

            public double ActualWidth { get; }

            public bool IsFullScreen { get; set; }

        }


You will see on little demo project how this works in real life.

First we need to add ScaleTransform in Page xaml code:

ScaleTransform ScaleX="1" ScaleY="1" x:Name="Root"

After that on Load method we need to save original width and height of application before entering fullscreen mode.We declare two variables to hold this values

private double width;

private double height;

and we set values:

 private void Load(object sender, RoutedEventArgs e)

        {

            height = this.Height;

            width = this.Width;

            Application.Current.Host.Content.Resized += new EventHandler(Resized);

            Application.Current.Host.Content.FullScreenChanged += new EventHandler(Resized);

        }

We add one method Resized to handle both our events 

Application.Current.Host.Content.Resized and  Application.Current.Host.Content.FullScreenChanged and inside this method we set how much application will resize on entering fullscreen mode by divide ActualWidth with old width and ActualHeight with old height.

 

private void Resized(object sender, EventArgs e)

        {

            if (Application.Current.Host.Content.IsFullScreen)

            {

                //if is fullscreen then zoom

                Root.ScaleX = (Application.Current.Host.Content.ActualWidth / width);

                Root.ScaleY = (Application.Current.Host.Content.ActualHeight / height);

            }

            else

            {

                //exit fullscreen remove zoom

                Root.ScaleX = 1;

                Root.ScaleY = 1;

            }

        }

And finally we add some button to change mode from fullscreen to normal on button click

private void Button_Click(object sender, RoutedEventArgs e)

        {

            Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;  

        }


 




 

Demo project : SilverlightFullscreenDemo.rar (1.59 mb)

Currently rated 3.3 by 3 people

  • Currently 3.333333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Radenko Zec Blog

Silverlight, C#, WCF, WPF,NET...