Lo sentimos, tu entrada no puede eliminarse en estos momentos. Vuelve a intentarlo más tarde.
02 noviembre
WPF Data Templates Part 2 - Value Converters
Sometimes the value you want to display needs to be transformed from the original data before being bound to a XAML element. For instance, formatting a telephone number, or adding brackets to a negative balance on an account. To accomplish this task a Value Converter is used. A Value Converter is simply a class that implements the IValueConverter interface (located in the System.Windows.Data namespace). This interface contains two methods, Convert, and ConvertBack. It is not necessary to implement the ConvertBack method unless you are persisting data back to a data source and need the reverse transformation from the visual back to the persisted value. It is important to remember that Value Converters can take in any value and return any type of object, for instance, an integer can be transformed into a string, and a string can be turned into a user control. In the example provided below, an integer value is converted to a User Control that has the ability to display a 5 star rating. Here is the XAML of the FiveStarRating user control which is made up of 5 paths in the shape of a star:
<Pathx:Name="Star1"Margin="0,15,5,0"Stroke="Black"StrokeThickness="2"StrokeLineJoin="Round"Data="M 0,0 l 10,0 l 5,-10 l 5,10 l 10,0 l -7,10 l 2,10 l -10,-5 l -10,5 l 2,-10 Z"/>
<Pathx:Name="Star2"Margin="0,15,5,0"Stroke="Black"StrokeThickness="2"StrokeLineJoin="Round"Data="M 0,0 l 10,0 l 5,-10 l 5,10 l 10,0 l -7,10 l 2,10 l -10,-5 l -10,5 l 2,-10 Z"/>
<Pathx:Name="Star3"Margin="0,15,5,0"Stroke="Black"StrokeThickness="2"StrokeLineJoin="Round"Data="M 0,0 l 10,0 l 5,-10 l 5,10 l 10,0 l -7,10 l 2,10 l -10,-5 l -10,5 l 2,-10 Z"/>
<Pathx:Name="Star4"Margin="0,15,5,0"Stroke="Black"StrokeThickness="2"StrokeLineJoin="Round"Data="M 0,0 l 10,0 l 5,-10 l 5,10 l 10,0 l -7,10 l 2,10 l -10,-5 l -10,5 l 2,-10 Z"/>
<Pathx:Name="Star5"Margin="0,15,5,0"Stroke="Black"StrokeThickness="2"StrokeLineJoin="Round"Data="M 0,0 l 10,0 l 5,-10 l 5,10 l 10,0 l -7,10 l 2,10 l -10,-5 l -10,5 l 2,-10 Z"/>
</StackPanel>
</Canvas>
</UserControl>
Source code for the FiveStarRating user control is as follows, contains the logic to fill the correct number of stars dependent on the Rating property of the instance:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ValueConverter
{
/// <summary>
/// Interaction logic for FiveStarRating.xaml
/// </summary>
publicpartialclass FiveStarRating : UserControl
{
publicint Rating
{
get { return (int)this.GetValue(RatingProperty); }
clearStar.Fill = new SolidColorBrush(Colors.Gray);
}
for (int i = 1; i <= ratingValue; i++)
{
Path starFilled = (Path)x.FindName("Star" + i);
starFilled.Fill = new SolidColorBrush(Colors.Goldenrod);
}
}
}
}
The Rating property of the FiveStarRating user control has been defined as a DependencyProperty, so it is possible to bind directly to it, but in this example, we will be using this user control as the result of a value converter transformation instead. The class definition and data being bound is defined in this previous blog post. The value converter we will implement will convert the integer ImageRating value and transform it into a bound FiveStarRating user control. The listing for the value converter is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
namespace ValueConverter
{
publicclass RatingConverter : IValueConverter
{
#region IValueConverter Members
publicobject Convert(objectvalue, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//in order to handle design time problems, handle null value case
if (value == null)
returnnew FiveStarRating();
FiveStarRating uc = new FiveStarRating();
uc.Rating = (int)value;
return uc;
}
publicobject ConvertBack(objectvalue, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
thrownew NotImplementedException();
}
#endregion
}
}
In order to utilize this Value Converter during data binding, it must first declare the namespace in the window tag, in this case the namespace is ValueConverter which resides in the current project assembly:
xmlns:local="clr-namespace:ValueConverter"
Then define an instance of the value converter class in Resources:
<local:RatingConverterx:Key="RatingConverter"/>
This instance of the RatingConverter can now be used in the data template. In order to utilize the rating converter, identify the resource (identified by the key in Resources, in this case RatingConverter) and assign it to the converter property of the binding expression.
This binding expression passes in the value stored in the ImageRating property of the object being bound into the Convert method of the RatingConverter value converter. The value converter then instantiates a new FiveStarRating user control, assigns the integer value to its Rating property, and returns the user control instead of the original integer ImageRating value. The user control is then rendered in the Label control.
El comentario que has escrito es demasiado largo. Acórtalo.
No has escrito nada. Vuelve a intentarlo.
No se puede agregar tu comentario en este momento. Vuelve a intentarlo más tarde.
Para agregar un comentario, necesitas permiso de tus padres. Pedir permiso
Tus padres han desactivado los comentarios.
No se puede eliminar tu comentario en este momento. Vuelve a intentarlo más tarde.
Has superado el número máximo de comentarios que se puede dejar en un día. Vuelve a intentarlo en 24 horas.
Se ha deshabilitado la capacidad de tu cuenta de dejar comentarios porque nuestros sistemas indican que podrías estar enviando correo no solicitado a otros usuarios. Si crees que tu cuenta se ha deshabilitado por error, ponte en contacto con el servicio de soporte técnico de Windows Live.
Para terminar de dejar tu comentario, realiza la siguiente comprobación de seguridad.
Los caracteres que escribas en la comprobación de seguridad deben coincidir con los de la imagen o el audio.
Para agregar un comentario, inicia sesión con tu cuenta de Windows Live ID (si utilizas Hotmail, Messenger o Xbox LIVE, ya tienes una cuenta de Windows Live ID). Iniciar sesión
¿No tienes una cuenta de Windows Live ID? Regístrate