(0 votes)

Tip: How to pass a parameter to a value converter?

0 comments   /   posted by Martin Mihaylov on Sep 09, 2008

If you're not familiar with the value converters read this. The methods generated by the VisualStudio when creating a custom class that implements System.Windows.Data.IValueConverter have several arguments. One of them is of type object and is called parameter.

public class DateTimeConverter : System.Windows.Data.IValueConverter
{
    public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )...
   
    public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )...
}

In this example we bind to an object of type Book:

public class Book
{
    public DateTime PublishDate { get; set; }
}

We can pass this argument from the code or from the Xaml:

Xaml

<TextBlock Text="{Binding PublishDate, Converter={StaticResource DateTimeConverter}, ConverterParameter=true}"/>

C#

Book myBook = new Book();
myBook.PublishDate = DateTime.Now;
 
Binding binding = new Binding( "PublishDate" );
binding.Source = myBook;
binding.Converter = new DateTimeConverter();
binding.ConverterParameter = true;

That's it!

Filed under: Binding


Comments

Comments RSS RSS
No comments

Add Comment