Gestion du Touch WP7 sous XNA4

30. September 2010 by Florian.ROUSSELET

Le nouvel OS mobile de Microsoft, Windows Phone 7, nous permet via l’écran tactile capacitif de gérer plusieurs points d’appuis. Nous allons voir dans cet article comment gérer cet écran au sein d’ XNA 4 et en faire une utilisation basique de détection de position.

Nous allons avoir besoin des logiciels et SDK suivants :

XNA Game Studio 4

Visual Studio 2010 + Windows Phone Tools

Maintenant voyons la marche à suivre pour la gestion du Touch. Tout d’abord, nous devons nous assurer que le Touch est disponible pour « lire » nos entrées dans la boucle Update.

 

TouchPanelCapabilities touchCap = TouchPanel.GetCapabilities();

 

             if (touchCap.IsConnected)

             {..}

 

Et l’on récupère l’état actuel du périphérique.

TouchCollection touches = TouchPanel.GetState();

 

On obtient donc une collection de « touches » (Points de pression) qui contient pour chaque touche ses coordonnées ainsi que l’état. Concernant ces états, il y a 4 possibilités :

-Invalid : Problème de reconnaissance
-Moved : La position a été mise à jour ou la position ne change pas
-Pressed : Il s’agit d’une nouvelle position
-Released : La position n’existe plus

 

Passons maintenant à la partie détection d’un appui sur l’écran.

if (touches.Count >= 1)

{

touchposition = (touches[0].Position);

}

 

Ici, on test si il y a au moins un point de pression de répertorier. Nous utilisons touchposition, qui est un Vector2 pour récupérer les coordonnées X et Y du point de pression. Attention ici il s’agit du point 0, l’écran du Windows Phone 7 peut gérer jusqu’à 4 points de pression. Il faudra donc penser lors du développement à tester les 4 points de pression. Ici à cause de l’émulateur seul le clic de la souris permet de simuler un point de pression. (Le nombre de point de pression possibles peut être vérifié via touchCap.MaximumTouchCount) .

Maintenant que nous avons ce Vector2 touchposition, nous pouvons l’utiliser comme nous voulons et très simplement. Par exemple pour afficher les coordonnées du point de pression.

Dans la boucle Draw, nous allons donc écrire les coordonnées du point de pression.

spriteBatch.Begin();        

string positionX = string.Format("X : {0}", touchposition.X);

spriteBatch.DrawString(font1, positionX,new Vector2(50,380), Color.White);

string positionY = string.Format("Y : {0}", touchposition.Y);

spriteBatch.DrawString(font1, positionY,new Vector2(50,420), Color.White);

spriteBatch.End();

 

font1 est un SpriteFont que j’ai ajouté au projet, il correspond à la police Segoe UI Mono. Celle utilisée par défaut par Windows Phone 7.


 

Faisons un petit résumé du code, commençons par la boucle Update :

TouchPanelCapabilities touchCap = TouchPanel.GetCapabilities();

if (touchCap.IsConnected)

{

TouchCollection touches = TouchPanel.GetState();

if (touches.Count >= 1)

{

touchposition = (touches[0].Position);

}

}

 

Et la boucle Draw pour dessiner notre résultat :

GraphicsDevice.Clear(Color.Black);

spriteBatch.Begin();

string positionX = string.Format("X : {0}", touchposition.X);

spriteBatch.DrawString(font1, positionX,new Vector2(50,380), Color.White);

string positionY = string.Format("Y : {0}", touchposition.Y);

spriteBatch.DrawString(font1, positionY,new Vector2(50,420), Color.White);

spriteBatch.End();

 

Voyons maintenant en image ce que l’on vient de réaliser :

Premier screen : Lancement de l’application, pas d’appui coordonnées = 0
Second screen : Simulation d’un point de pression via un clic souris, mise à jour des coordonnées
Troisième screen : Autre clic, changement des coordonnées

Maintenant c’est à votre tour d’utiliser le Touch. A vos Visual Studio !

C#, Visual Studio 2010, Windows phone 7, XNA , , ,

Windows Phone 7 et une architecture orientée service (WCF)

Le but de cet article est de réussir à afficher la liste des clients qui sont en base de données tout cela à travers un web service WCF.

 

Pour suivre cet article, voici les outils que j’ai utilisé :

- Microsoft Visual Studio 2010

- Microsoft Visual Studio 2010 Express for Windows Phone que vous pouvez télécharger par ici : http://developer.windowsphone.com/Default.aspx

- SQL Server 2008 et la base de données Northwind
- L’accès aux données : Entity Framework 4

 

1) Création de la couche accès aux données

 

Nous allons déjà dans un premier temps créer notre accès aux données. Cela sera tout simplement une bibliothèque de classe.
Dans cette bibliothèque de classe, créer votre “ADO.NET Entity Data Model” qui pointera vers la base de données Northwind. Les tables utilisées seront “Customers” et “Orders”.

 

image

Voici à quoi ressemble la bibliothèque de classe :

 

image

 

 

 

2) Création du web service WCF

 

Créer un nouveau projet de type  “WCF Service Application”.
Supprimer Service1.svc et son interface car les noms ne sont pas explicites.
Ajouter à ce projet un “WCF Service” que j’ai nommé WSCustomers et IWSCustomers pour l’interface.

 

Commençons par l’interface avec 3 méthodes :

 

[ServiceContract]
public interface IWSCustomers
{
    [OperationContract]
    List<Customers> GetAllCustomers();

    [OperationContract]
    Int32 GetNumberOfCustomers();

    [OperationContract]
    List<Orders> GetCustomerOrders(string customerId);
}

 

Puis nous les implémentons dans notre classe WSCustomers de cette manière :

 

public class WSCustomers : IWSCustomers
{

    #region Customers
    /// <summary>
    /// Retourne tous les clients sous forme de liste
    /// </summary>
    /// <returns></returns>
    public List<Customers> GetAllCustomers()
    {
        NorthwindEntities entities = new NorthwindEntities();
        var customers = from cust in entities.Customers
                        select cust;

        return customers.ToList();
    }

    /// <summary>
    /// Retourne le nombre de clients sous forme d'un entier
    /// </summary>
    /// <returns></returns>
    public int GetNumberOfCustomers()
    {
        NorthwindEntities entities = new NorthwindEntities();
        var numberOfCustomers = (from cust in entities.Customers
                                 select cust).Distinct().Count();

        return numberOfCustomers;
    }

    /// <summary>
    /// Récupère toutes les commandes pour un utilisateur sous forme de liste
    /// </summary>
    /// <param name="customerId"></param>
    /// <returns></returns>
    public List<Orders> GetCustomerOrders(string customerId)
    {
        NorthwindEntities entities = new NorthwindEntities();
        var orders = from o in entities.Orders
                     where o.CustomerID.Equals(customerId)
                     select o;

        return orders.ToList();
    }

    #endregion
}

 

Maintenant que l’on a terminé notre service web, nous allons passer à notre application Windows Phone 7.

 

3) Création de l’application Windows Phone 7

 

Une fois dans Microsoft Visual Studio 2010 Express for Windows Phone il vous faudra créer une "Windows Phone Application”.

Dans la MainPage.xaml nous allons mettre 2 TextBlock et une ListBox.

 

 

 

<Grid x:Name="TitleGrid" Grid.Row="0" Background="#FF43466E">
    <TextBlock Text="Customers List" x:Name="textBlockPageTitle" 
			   Style="{StaticResource PhoneTextPageTitle1Style}" />
    <TextBlock Text="{Binding}" Name="txtNumberOfCustomers" />
</Grid>

<Grid x:Name="ContentGrid" Grid.Row="1">
    <ListBox Name="lstCustomers"/>
</Grid>

 

 

Le premier TextBlock “textBlockPageTitle” n’est ni plus ni moins que le titre qui se trouvera en haut à gauche de l’écran.
Le deuxième TextBlock “txtNumberOfCustomers” recevra le résultat de la méthode créée dans le Web Service qui se nomme : GetNumberOfCustomers().

Comme vous vous en doutez, la listbox recevra la liste des clients soit la méthode GetAllCustomers() dans notre Web Service.

 

Passons au code-behind de la page “MainPage.xaml” :

- Il vous faudra au préalable ajouter le web service à votre application. Clic droit sur votre application WP7 puis “Add Service Reference”. Vos méthodes seront accessibles. J’ai nommé ma référence de service WSCustomers.

 

Nous allons déjà afficher les clients dans notre listbox

 

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
    WSCustomersClient service = new WSCustomersClient();
    service.GetAllCustomersAsync();

    service.GetAllCustomersCompleted += 
    new EventHandler<GetAllCustomersCompletedEventArgs>
(
service_GetAllCustomersCompleted
); } void service_GetAllCustomersCompleted(object sender,
GetAllCustomersCompletedEventArgs e) { if (e.Result != null) { this.lstCustomers.ItemsSource = e.Result; } }

Il faudra ajouter dans le XAML le Binding pour que cela fonctionne.
Voici les deux propriétés à rajouter à la listbox “lstCustomers” :

 

ItemsSource="{Binding}" DisplayMemberPath="CustomerID"

 

Dans cette listbox on affichera donc les CustomerID.

 

Même principe pour l’affichage du nombre de clients dans le TextBlock “txtNumberOfCustomers”.

Je rajoute le code suivant au “Load” de la page :

service.GetNumberOfCustomersAsync();

service.GetNumberOfCustomersCompleted += 
new EventHandler<GetNumberOfCustomersCompletedEventArgs>
(
service_GetNumberOfCustomersCompleted
);

 

Puis la méthode :

 

void service_GetNumberOfCustomersCompleted(object sender, 
GetNumberOfCustomersCompletedEventArgs e) { this.txtNumberOfCustomers.DataContext = e.Result.ToString() + " customers"; }

Voici le résultat de la première page “MainPage.xaml” en image :)

 

image

 

4) Création d’une autre page XAML qui aura pour but d’afficher les commandes du client que l’utilisateur aura sélectionné

- Créer une autre page XAML “CustomerOrders.xaml”.

Je vais me baser sur l’évènement “SelectionChanged” de ma listbox “lstCustomers”.

 

Voici la méthode :

 

private void lstCustomers_SelectionChanged(object sender, 
SelectionChangedEventArgs e) { Customers customerSelected = (Customers)lstCustomers.SelectedItem; if (customerSelected != null) { string customerId = customerSelected.CustomerID; string uri = String.Format("/CustomerOrders.xaml?customerId={0}",
customerId); this.NavigationService.Navigate(new Uri(uri, UriKind.Relative)); } }

 

Je récupère tout simplement le “Customers” qui a été sélectionné.

Je passe à ma page CustomerOrders.xaml une donnée qui est le customerId.

 

Pour finir, j’utilise la méthode Navigate de NavigationService pour rediriger l’utilisateur vers ma page CustomerOrders.xaml.

 

Pour plus d’informations sur la navigation inter-pages, je vous invite à lire cet article : http://blogs.codes-sources.com/pi-r/archive/2010/05/20/windows-phone-7-ndash-navigation-inter-pages-avec-la-propriete-page-navigationservice.aspx

 

Passons à notre page CustomerOrders.xaml et à son code XAML.
J’y ai ajouté un simple StackPanel et une listbox :

 

<StackPanel Grid.Row="1">
    <ListBox Name="lstCustomerOrders"/>
</StackPanel>

Le code behind de CustomerOrders.xaml sera :

protected override void OnNavigatedTo(
Microsoft.Phone.Navigation.PhoneNavigationEventArgs e) { base.OnNavigatedTo(e); if (this.NavigationContext.QueryString.ContainsKey("customerId")) { string customerId = this.NavigationContext.QueryString["customerId"]; this.ApplicationName.Text = "Orders for : " + customerId; WSCustomersClient service = new WSCustomersClient(); service.GetCustomerOrdersAsync(customerId); service.GetCustomerOrdersCompleted += new EventHandler<GetCustomerOrdersCompletedEventArgs>
(
service_GetCustomerOrdersCompleted
); } } void service_GetCustomerOrdersCompleted(object sender,
GetCustomerOrdersCompletedEventArgs e) { if (e.Result != null) { this.lstCustomerOrders.DataContext = e.Result; } }

 

Ici on “override” la méthode OnNavigatedTo. Le principe est simple, nous naviguons de la page “MainPage.xaml” vers la page “CustomerOrders.xaml”, donc lorsque l’on navigue vers la page CustomerOrders.xaml on atterrit directement dans la méthode OnNavigatedTo.

Dans cette méthode je récupère le QueryString passé tout à l’heure.

string uri = String.Format("/CustomerOrders.xaml?customerId={0}", customerId);


Il vous faudra ajouter dans le XAML le binding à la listbox “lstCustomerOrders” de cette manière :

ItemsSource="{Binding}" DisplayMemberPath="OrderID"

 

5) Résultat en image

 

imageimage

 

En effet certains me diront que cette application n’est pas très belle.
Si vous souhaitez améliorer le rendu il existe des add-in pour Microsoft Expression Blend 4 :

- Add-in Preview 2 for Windows® Phone

- Software Development Kit (SDK) Preview 2 for Windows Phone

 

Rendez-vous sur cette page pour en savoir plus sur ces outils : http://www.microsoft.com/downloads/details.aspx?familyid=47F5C718-9DEC-4557-9687-619C0FDD3D4F&displaylang=en

 

 

J’espère que cet article vous a donné une idée des applications réalisables sur Windows Phone 7 :)

 

Charles.

Windows phone 7 , ,

Deployer et lancer un jeu XNA 4.0 sur émulateur WP7 sans visual studio.

8. June 2010 by Thomas.Trentin

 

Deployer et lancer un jeu XNA 4.0 sur émulateur WP7 sans visual studio.

1 . Pré-requis:

 

XNA Game Studio 4.0.

CTP April Refresh (Visual Studio 2010 Express For Windows Phone) .

 

Ce tutorial a pour but de vous montrer comment déployer un programme XNA 4.0 sur l'émulateur Windows Phone 7 de microsoft (fournit avec la April Refresh), sans avoir nécessairement le code sous la main.

Ceci peut ête très pratique notament afin de faire tester votre application à une personne tierce sans lui livrer votre code.

 

2 . Deploiement :

 

Créez votre projet XNA 4.0 et compilez le.

Pour une question de simplicité, les fichiers récupérés seront tous mis dans un dossier commun.

Allez dans le dossier de sortie de compilation (dans mon cas bin\Windows Phone\Debug) et récupérez le « .xap » généré, qui est l’archive contenant votre jeu.

Dans mon cas, il s’agit de « XnaGraphicsDemo.xap ».

 

Récupérez aussi le GameThumbNail.PNG.

Allez ensuite dans le dossier : \obj\Windows Phone\Debug et récupérez le fichier « XapCacheFile.xml ».

Il contient les informations sur les ressources et les fichiers de votre application, contenus dans le xap.

 

Enfin, allez dans le dossier properties et ouvrez le fichier AssemblyInfo.cs :

Il faut récupérer la valeur notée sur cette ligne :

Dans notre cas, la valeur à noter est donc : "ba971892-de57-4fa4-b7e6-65d9d6da5af7".

Cela correspond à l’ID de l’application, et est indispensable afin de l’utiliser sur Windows Phone (aussi bien pour le déploiement que pour l’installation).

Vous devez maintenant avoir un dossier contenant tous les fichiers demandés jusqu’ici, ce qui doit ressembler à ceci :

 

Ouvrez maintenant une invite de commande.

Faite glisser le fichier « wp.exe », qui est dans le dossier C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\Tools (chemin dépendant de l’installation sur votre machine).

Cela devrait ressembler à ceci :

Tappez maintenant  « install », qui permet de déployer votre application sur l’émulateur, puis faite glisser dans l’invite de commande le fichier « xap », coller le GUID copié précédemment, et enfin faites glisser le fichier thumbail et le fichier xml.

Terminez la commande avec l’instruction « /clean ».

Apuyez sur entrée : l’émulateur se lance et installe votre application automatiquement.

Lorsque le lancement de l’émulateur et l’installation de votre application est terminée, vous devez maintenant avoir l’écran d’accueil d’affiché sur votre émulateur :

 

Vous n’avez plus qu’à taper dans votre invite de commande la ligne comportant le « launch » : (en remplaçant bien sûr la  valeur après le launch par le GUID de VOTRE application) : 

 

Voici le résultat :

C#, Visual Studio 2010, Windows phone 7, WPF, XNA ,

Creating your first MVVM silverlight application on windows phone 7.

The goal of this tutorial is to create an MVVM driven twitter mini client application for windows phone 7. We’ll do the exact same twitter client Scott Guthrie did in the MIX 10 presentation except we’ll follow the MVVM pattern. 
So here’s how we’d want it to look like.

The source code for this tutorial is also available.

1) Why MVVM ?

MVVM is a design patter, better for testing and for big enterprise projects since there wouldn’t be any code behind in your view, everything would be exposed and controlled by your ViewModel – so easier to test.
(Here’s a more detailed guide about the MVVM pattern).

Here’s a schema summarizing the pattern:

MVVM_pattern_diagram_thumb

2) In order to develop for Windows Phone 7, you need to get the free SDK here, the current version is the April CTP refresh. (Visual Studio 2010 Express comes with the tools you can download, so developing for windows phone 7 can be absolutely free).

Let’s Start coding!

Open Visual Studio and create a new project using the “Silverlight for Windows Phone” Tab and choosing the “Windows Phone Application” template.

Let’s start of by creating a new class called: ViewModelBase and make it implement the INotifyPropertyInterface.

This is going to be the class we’re going to derive from all of our ViewModels.

Now let’s add some properties in this Base class in order to get save some lines of code and not repeat ourselves in the other ViewModel classes we’re going to write.

protected void OnNotifyPropertyChanged(string p)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(p));
    }
}       
public event PropertyChangedEventHandler PropertyChanged;

This basically says whenever my property is changed the event PropertyChanged is launched.

Let’s create our View now.

Open up the MainPage.xaml.

I’m going to add a TextBox, a button and a listbox unto the design view (you can manipulate the controls and dimension them to whatever you want from the designer view etc ..)

So here’s how my view looks like right now:

view

Now let’s modify our listbox in order to contain an image and the status update. (many ways you can do this, you can ofcourse do it from Blend), but this isn’t the purpose of this tutorial. So we’ll keep it simple.

Add a Image then a textbox for the message and another for the username inside the listbox template while editing the xaml.

So our Xaml for the listbox can look like this:

  <ListBox Height="500" HorizontalAlignment="Left" 
                     Margin="20,115,0,0" 
                     Name="listBox1" VerticalAlignment="Top" Width="440">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Height="100" Width="100" 
                                   VerticalAlignment="Top" Margin="0,10,8,0"/>
                            <StackPanel Orientation="Vertical">
                                <TextBlock />
                                <TextBlock   />
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

 

Now let’s add our ViewModel for this specific View.

Create a new folder called “ViewModels” and then a new class in that folder named: “MainViewModel”

Make that class derive from our “ViewModelBase” class.

So let’s think about what we want exactly:

* When the button Look up is pressed we want the above page title to change to “Whatever we put in the textbox” ‘s Feed”.

* When the button Look up is pressed, we get the status updates for the specific user entered in the textbox.

Okay let’s jump into that, remember there shouldn’t be any code behind on my view that’s event driven specific etc..

First let’s start off by linking our View to the ViewModel we just created.

There are two ways of doing this, one from the View XAML directly, the other in the code behind while calling the constructor of the View.

The most common method is the second so we’ll do that.

Open the code behind of the MainPage View.

Add the namespace of the ViewModels, create a new variable of type “MainViewModel”.
Set the DataContext of the View as the MainViewModel variable we just created.

private MainViewModel _mainViewModel = new MainViewModel();

        public MainPage()
        {
            InitializeComponent();
            DataContext = _mainViewModel;
        }

 

Here’s the inside of our MainPage class now.

Let’s create now our TwitterItem class:

Create a new class called TwitterItem and add the following properties (there’s nothing different here from ScottGu’s post) : Username , Message, ImageSource.

Then add a static method that we’ll help us parse the xml returned and return a list of TwitterItems.

So overall our class looks like this now:

public class TwitterItem
{
    public string Username { get; set; }
    public string Message { get; set; }
    public string ImageSource { get; set; }

    public static List<TwitterItem> GetTweetsFromResponse(String Response)
    {
        List<TwitterItem> lsttweets = new List<TwitterItem>();

        XElement xmlTweets = XElement.Parse(Response);
        lsttweets = (from tweet in xmlTweets.Descendants("status")
                    select new TwitterItem
                    {
                        ImageSource = tweet.Element("user").Element("profile_image_url").Value,
                        Message = tweet.Element("text").Value,
                        Username = tweet.Element("user").Element("screen_name").Value
                    }).ToList();

        return lsttweets;
    }
}


Now let’s go back to our MainViewModel class.

I’m going to need a property for the textbox text (which will be the username for the feeds we want to get), another one for the title, and finally a RelayCommand for the Button.

What? RelayCommand? what’s that? it’s a helper from the MVVM light toolkit developed by Laurent Bugnion
(He also presented the Toolkit in MIX 10)

The toolkit works on WPF, Silverlight and WP7.

Now why would we need this?It’s simply a really big time saver + commands don’t exist on WP7 because WP7 use Silverlight 3.

RelayCommands helps us link commands on methods, you’ll understand this in a minute.

So first let’s add the dlls from the toolkit you can get them here.

references

Now that’s done we can add our RelayCommand.

So this how class looks like now:

public class MainViewModel : ViewModelBase
    {
        public string strUsername { get; set; }
        public RelayCommand GetTweetsCommand { get; private set; }
    }

 

Now we need an ObservableCollection for the tweets, and this collection will be the item source of our listbox.

private ObservableCollection<TwitterItem> _lstTweets;
public ObservableCollection<TwitterItem> LstTweets
{
    get
    {
        return _lstTweets;
    }
    set
    {
        if (_lstTweets != value)
        {
            _lstTweets = value;
            OnNotifyPropertyChanged("LstTweets");
        }
    }
}

Finally our last property needed, is the Title one since it’s going to be binded to the title in order to set the Title to “screen name” ‘s feed.

private string _title;
public string Title
{
    get
    {
        return _title;
    }
    set
    {
        if (_title != value)
        {
            _title = value;
            OnNotifyPropertyChanged("Title");
        }
    }
}


Now let’s write the methods to get the tweets from the twitter api (one will be used for the async call,
and the other for the response):

private void GetTweetsCall(string screenName)
  {
      WebClient client = new WebClient();
      client.DownloadStringCompleted += 
          new DownloadStringCompletedEventHandler(twitter_Response);
      client.DownloadStringAsync(
          new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name="
              + screenName));
  }

  private void twitter_Response(object sender, DownloadStringCompletedEventArgs e)
  {
     if (e.Error == null)
      {
          LstTweets = TwitterItem.GetTweetsFromResponse(e.Result);
      }
  }

 

Finally we have to add the constructor and in that constructor we’re going to link our relay command to the method that calls the twitter api, and set the “Title” property with the txtUsername property + “’s feed”:

public MainViewModel()
 {
         GetTweetsCommand = new RelayCommand(() =>
             {
                 Title = txtUsername + "'s Feeds";
                 GetTweetsCall(txtUsername);
             }
         );
 }


All this is nice, but that’s not enough, we need to bind everything on the View.

So for the title TextBlock, we bind the text to the Title:

<TextBlock Text="{Binding Title, Mode=OneWay}" 
                       Style="{StaticResource PhoneTextPageTitle2Style}"/>

 

Repeat the same thing for the TextBox but instead of setting the Mode OneWay you have to set it TwoWay because we’re using the Text written in the TextBox by the user in our ViewModel.

<TextBox Height="72" HorizontalAlignment="Left" Margin="31,37,0,0" 
                     Text="{Binding txtUsername,Mode=TwoWay}" 
                     VerticalAlignment="Top" Width="275" />

Now we have to bind the listbox Item source to our ObservableCollection.

  <ListBox Height="500" HorizontalAlignment="Left" 
                     Margin="20,115,0,0" 
                     VerticalAlignment="Top" 
                     Width="440" ItemsSource="{Binding LstTweets, Mode=OneWay}">

So what’s left? Binding the image and 2 textblocks inside our listbox.

   <Image Height="100" Width="100"  Source="{Binding ImageSource , Mode=OneWay}"
                                   VerticalAlignment="Top" Margin="0,10,8,0"/>
                            <StackPanel Orientation="Vertical">
                                <TextBlock  Text="{Binding Username , Mode=OneWay}"  />
                                <TextBlock  Text="{Binding Message , Mode=OneWay}"  
                                           />
                            </StackPanel>


Now how do we set the Command on our button in wp7 based on Silverlight 3 where commands weren't supported ?  With the MVVM light toolkit!

It’s easier to do this with Blend by just drag and dropping , but not the purpose of this tutorial ;) ..

So just copy/paste this in your button XAML:

  <Button Content="Look up" Height="70" 
                    HorizontalAlignment="Left" Margin="300,37,0,0" 
                    VerticalAlignment="Top" Width="160">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Click">
                        <GalaSoft_MvvmLight_Command:EventToCommand 
                            Command="{Binding GetTweetsCommand, Mode=OneWay}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </Button>

Add the necessary namespace imports :

 xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
 xmlns:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP7" 
  

As you noticed the Command Binding in the eventTrigger is set to the RelayCommand we created in our ViewModel.

Then a little bit of styling on our View in order to make it look good.

Run your application now!

Type in a screen name inside the textbox and click the “Look up” button and this is the result:

result

Hope you enjoyed this article, MVVM isn’t an easy concept, but a lot of helpers out there, I personally really like MVVM light toolkit. I'll do my best to write more articles on windows phone 7 and MVVM!

In the mean time you can get the source code here.

C#, Silverlight, Windows phone 7 , ,