Xaml WPF Binding ValueConverter: un exemple simple

Voici comment utiliser un converter lors d'un binding wpf.

J'ai écris ici un petit jeu ou l'utilisateur doit trouver un nombre, hardcodé, mais peu importe.

Il écrit un nombre dans une TextBox, et un label lui indique si la valeur qu'il à entrée est >, < ou = au nombre cherché : 

 

La conversion se fait de la sorte : le label bind son content sur le text de la TextBox, mais le modifie lors du binding.

Voici le code, ce sera plus clair Sealed (il est tard)

public class FindTheNumberConverter : IValueConverter
{
    int toFind = 782;

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        String str = "";
        try
        {
             int tap = Int16.Parse((string)value);
             if (tap == toFind)
                str =
"Parfait, il s'agit bien de " + toFind;
             else
             {
                  if (tap > toFind)
                        str =
"le nombre a trouver est plus petit que celui-ci (" + tap + ") !";
                  if (tap < toFind)
                        str =
"le nombre a trouver est plus grand que celui-ci (" + tap + ") !";
              }
         }
         catch
         {
              str =
"ce tap n'est pas un nombre!";
         }
         return str;
     }

     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
     {
throw new Exception("The method or operation is not implemented."); }
}

Et voici à quoi ressemble le xaml :

<Window x:Class="Test_Convertor.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:MyApp="clr-namespace:Test_Convertor"
Title="Window1" Height="300" Width="300">

<Window.Resources>
    <MyApp:FindTheNumberConverter x:Key="FindTheNumber"/>
</Window.Resources>

<Grid>
   
<TextBox HorizontalAlignment="Stretch" VerticalAlignment="Top" Name="MyTextBox" Height="26"/>

    <Label Content="{Binding ElementName=MyTextBox, Path=Text, Converter={StaticResource FindTheNumber}}"
     
Height="26" HorizontalAlignment="Stretch"/>

</Grid>
</Window>

Posted on 19/08/2007 18:33:00 by Togis

Permalink | Commentaires (0) | Post RSSRSS comment feed |

Categories: WPF | Tips | Binding

Tags:

Actuellement noté 1.0 par 1 personne(s)

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

Billets liés

Ajouter un commentaire


(Affichera votre icône Gravatar)  

  Country flag





Live preview

novembre 21. 2008 18:54