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
(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>