Posts Tagged ‘Silverlight 3’

Hi guys, back again with a question more than a post. Last few days I’ve played a little with Silverlight Toolkit and a question came out with Transitioning Content Control in the Toolkit: “is it useful???”.

What the content Control does i to show with a nice transition an element (e.g. from a list), but without showing the others.

Below the example that you can try:

Install Microsoft Silverlight

I think that it’s stressful for a user don’t see what’s next element and what’s the previous one at least. It may be need something more. Let’s see anyway how to use it :)

First of all add a reference of Silverlight layout toolkit to your project

image

Then add the reference into XAML (i called it layoutToolkit):

<UserControl
    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" x:Class="TransitionContentExample.MainPage"
    d:DesignWidth="640" d:DesignHeight="480">
  <Grid x:Name="LayoutRoot">

      <layoutToolkit:TransitioningContentControl
        x:Name="_transitionControl"
        Content="TransitioningContentControl"/>

    </Grid>
</UserControl>

Now we need a little template to display data, really easy template, with a soft shadow to make it look a little better:

<layoutToolkit:TransitioningContentControl
            x:Name="_transitionControl"
            Content="TransitioningContentControl">

            <!--Add a little effect-->
            <layoutToolkit:TransitioningContentControl.Effect>
                <DropShadowEffect Color="Black" BlurRadius="10" ShadowDepth="10" Direction="315"/>
            </layoutToolkit:TransitioningContentControl.Effect>

            <!--Add a little template. Change the template with something interesting :) -->
            <layoutToolkit:TransitioningContentControl.ContentTemplate>
                <DataTemplate>
                    <Grid>
                        <Rectangle Width="200" Height="180" RadiusX="10" RadiusY="10" Fill="BlueViolet"/>
                        <TextBlock Text="{Binding}" FontSize="15" Foreground="White" FontWeight="Bold"
                                   VerticalAlignment="Center" HorizontalAlignment="Center"/>
                    </Grid>
                </DataTemplate>
            </layoutToolkit:TransitioningContentControl.ContentTemplate>

        </layoutToolkit:TransitioningContentControl>

And now we need to write a little C# code to make it work.

Lets create a list of strings that will be passed as a content and displayed in the textblock (since it has a Binding) we can do it easily.

private List<String> _fakeItems = new List<string>();
        public MainPage()
        {
            InitializeComponent();

            Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 20; i++)
            {
                _fakeItems.Add("Something " + i);
            }

            //assign the first element immediately
            _transitionControl.Content = _fakeItems[++counter];
        }

and then override the “mouse left” event to change the items:

private int counter = 0;
        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            //checks if counter will index out of range
            counter = counter + 1 == _fakeItems.Count ? 0 : counter;

            base.OnMouseLeftButtonDown(e);
            _transitionControl.Transition = "UpTransition";
            _transitionControl.Content = _fakeItems[++counter];
        }

(the link @ the src code)

As you seen nothing really difficult, but I can’t really see how to use it :| any suggestion?

 

-dave

Introduction

Understanding Design Patterns is not complicated at all, use them involves quite experience, but explain them turned out to be kinda difficult. Do people will understand the power of Design Patterns? Well let’s try!

A Design Pattern is a way we organize our code architecture. We should come up without mixed roles in the same class: one class, one role. Instead talking about class we should call them layers, because a class can have specific commitments that involve nested classes, but with the same role. So we’ll call them generally layers. At the end of the coding process we should have one layer and one role. At this point we would have lots layers not knowing each others, and we let them communicate using some middle layer. The point is to loosely couple different layers, to better split roles, and enhance them while focusing onto that particular task. Let me explain this with a simple example, taking into account two layers that has to communicate, but do not know each-other:

clip_image002

So we have a model (which is a layer) that contains data, a view (another layer) that has to show this data and someone (a middle layer) that makes this happen. This is a typical Design Pattern, where we separate the code to handle it better while refining. This implementation way takes into account some good principles:

· Maintainability: easy to handle code

· Scalability: easy to increase application’s features

· Optimization: we can optimize our code easily

· Code Reuse: we can reuse code almost with copy & paste

· …lots more, but these are good enough (you can add some in comments J)

The Process

The implementation process seems to be straight-forward but it’s not. Not always by the way! First of all we are still missing the middle layer, which takes something as input and sends something out; for example takes data from models and informs the view that some data is available. This process of taking/sending data needs to be synchronized…not easy at all.

At this point we introduce the power of our technology: Silverlight 3!

Silverlight 3 is a technology created and developed by Microsoft, and is meant to run on browsers. It’s a cross-browser platform. To develop applications in Silverlight we use two different coding languages:

· XAML: eXtended Application Markup Language, based on XML but application oriented. With XAML is possible to create objects instances simply with tags: <Button/> is a valid instance of a button and is the same of new Button() we all know!

· C#: (Cool and Sharp) is a powerful programming language, general purpose, also created and developed by Microsoft. It’s a first class language into the .NET Framework, and is powerful like C++ and easy like Java. If you already know C# you know what I mean, otherwise you should try it! Oh yeah, I was forgetting it…it’s open source.

Back into our mind-flow learning process, we were talking about synchronizing the view with the data contained in models. For this example we’ll use XAML to create the View and C# to create the middle layer and the models. How the View and the Model look like?

In the left the View and in the right the Model in C#.

clip_image004 clip_image006

As we can notice the model it’s just a C# class ready to hold some data. The view it’s a form that is ready to show some data. Now the middle layer could be a data collection, like a List, that takes data as input and release this data on demand. In the common implementation, like a Model-View-Presenter (MVP) we call our mysterious middle layer: The Presenter.

clip_image002

The above schema shows how the Presenter handles the messages, data and input from the view and the model.

In Silverlight, like WPF (Windows Presentation Foundation) we can take advantage of powerful Data Binding in order to create a more flexible Design Pattern: Model-View-ViewModel. We already know the role of the view and the model, and the role of the ViewModel does not change respect to the Presenter. At this point the reader could ask : “so what’s the point to have another design pattern?”. Well it’s quite easy to implement the MVP, so if you feel satisfied by this description you are ready to create an app. If you still feel empty, well let’s see further what’s on the plate J!

In MVP we understood that “P” knows both model and the view. The ViewModel, does not know the view…and neither the model! Here the world seems to invert its common rules. Everybody here collaborates without knowing each-other! So, how the ViewModel can bring the magic into our view without knowing it? The Data Binding is the Key!

Let me drop few lines about Data Binding in Silverlight 3. The binding is essentially a symbolic link between two objects, like pointers in C++. The difference is that binding is resolved via reflection (trough types and derivations), not via physical memory addresses. Since we create the view with XAML we make data binding in XAML. For example imagine that you have a TextBlock that should display a text after a button click:

<TextBlock x:Name=”_myText”/>

Public void Button_Click(object sender, EventArgs e) {

_myText = “Hello Text!”;

}

The Binding way:

<TextBlock x:Name=”_myText” Text=”{Binding}”/>

Public void Button_Click(object sender, EventArgs e) {

_myText.DataContext = “Hello Binding!”;

}

So we see that the data is passed through the DataContext, and the objects derives its self which property needs what from DT. This particular way of Binding can be extended and categorized. It could be:

· One Time: data set only once

· One Way: data flows from one direction, manly input

· Two Way: data flows in output and input, be careful on using this since it’s not that easy to maintain

So the View does not know the ViewModel, but waits for input; the ViewModel does not know how the view is configured, and passes the Data via DataContext. A widely example could be the following one:

We have a container that holds two TextBlock and we pass the data via DataContext’s container and it takes care of redistributing in broadcast through it children. We pass an entire class!

<StackPanel x:Name=”_stack”>

<TextBlock Text=”{Binding Name}”/>

<TextBlock Text Text=”{Binding Surname}”/>

</StackPane
l>

public void Button_Click(object sender, EventArgs e) {

_stack.DataContext = new Person { Name=”Dave” Surname=”SL”};

}

The Binding is redirected to the Name and Surname path. That’s it :) .

The Remake

And finally we got to the fun part of this! Yeah! Congrats to readers, they got thru all of this madness ;) . Just joking, it was fairly easy.

So how we can make this data passing really really easy and understandable? I mean both data binding and M-V-VM Design Pattern? The Data Binding was as easy as possible, the M-V-VM not at all.

To get ready follow this steps:

1. Open Expression Blend 3 and create a new standard Silverlight 3 Project

2. Create a view like the following one: clip_image010 and give a name to objects 4(_model), 5 (_viewmodel), 6(_view).

3. Now select the 6th object (TextBlock) and go to the Properties Panel in Common Properties, where you edit the text. Press the little square.

 clip_image012

4. Now you get a menu. Press on Data Binding

 clip_image014

5. You’ll have the following screen:

clip_image016

You can’t click ok. Select _viewmodel and then click OK. Now you have a OneWay Binding from _view to _viewmodel. So the View takes the input text from _viewmodel. The ViewModel does not know the view, but passes data to it! If you now change the the ViewModel text automatically changes the View text. Nice uh? J Not finished yet!

6. Now select the 5th object and do the passes 3 and 4. This time link _viewmodel with _model. Select Two Way, instead OneWay. Remember to set Text as target property. Two Way means that _viewmodel can get and send data. Gets data from _model, and sends data to _view.

So run the project and start typing into the textbox (object 4): automatically the view reflects the changes and so the view.

Now you are done to show how cool is M-V-VM, without write a single line of code! Now is as easy as possible :) . Any other ideas?

-Dave.

Hi guys, on Tuesday 1 Dec 2009 I’ll be @ Trieste having a speech on Silverlight 3.
Everybody there seems to be so excited, and me too :D .

Here goes the agenda:

  • Enhancing design time: Designers vs Developers
  • Layouts
  • Sketchin’ applications
  • Design Patterns: Model-View-ViewModel in Silverlight 3
  • Data gathering and viewing
  • It’s pretty hard agenda, isn’t it…hu? For any questions do not hesitate to post comments here, I’ll be pleasured to answer you guys ;)

    locandina_seminario_trieste

    -dave