Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically using a value converter in C# in Silverlight

Tags:

c#

silverlight

I have a C# Silverlight application. In this application I have defined a value converter that I am using in the XAML. I have run into a situation where I need to programmatically use this value converter in my code behind. My question is, how do I do that? In XAML, I am using my value converter as follows:

<TextBlock x:Name="myTextBlock" Text="{Binding Mode=OneWay, Path=FirstName, Converter={StaticResource myConverter}, ConverterParameter=NotSet}" />

How do I use this converter in my code-behind?

Thanks!

like image 468
user208662 Avatar asked Feb 02 '11 16:02

user208662


2 Answers

If you just want to call the converter explicitly in the code behind, just use the converter class just like any other class and call its Convert() methos with appropriate parameters

YourConverter conv = new YourConverter();
conv.Convert(...)
like image 83
Jobi Joy Avatar answered Nov 08 '22 11:11

Jobi Joy


I personally add a static method to the converter like so:

public static object Convert(object value)
{
    return new MyConverter().Convert(value, null, null, CultureInfo.CurrentCulture);
}

You can then use this in code like so:

MyConverter.Convert(valueToConvert);

You can even change the return type and cast the result before returning to make usage easier.

like image 45
James Coyle Avatar answered Nov 08 '22 10:11

James Coyle