Question

Let's say I have some enumeration, like:

enum MyEnum { value1, value2 }

and value converter:

[ValueConversion(typeof(MyEnum), typeof(string))]
class MyEnumToString : IValueConverter
{
    ...
}

Now I want to print two MyEnum values converted using MyEnumToString:

<Window.Resources>
    <converters:MyEnumToString x:Key="myEnumToString"/>
</Window.Resources>

...

<TextBlock Text="{here I want to print value1 converted by myEnumToString}"/>
<TextBlock Text="{here I want to print value2 converted by myEnumToString}"/>

How can I do this? Note that there is no data binding here, just two values.

Was it helpful?

Solution

Converter used together with a Binding, quote from MSDN:

IValueConverter: Provides a way to apply custom logic to a Binding.

If you want to associate a value converter with a Binding, create a class that implements the IValueConverter interface and then implement the Convert and ConvertBack methods.

Therefore, you need to write this:

<TextBlock Text="{Binding Path=value1, Converter={StaticResource myEnumToString}}" ... />    

If this values located in ItemSource or for root Control defined DataContext, try this:

<TextBlock Text="{Binding Converter={StaticResource myEnumToString}}" ... />

Either like this:

<TextBlock Text="{Binding Path=., Converter={StaticResource myEnumToString}}" ... />

In this case, Text="{Binding Path=.}" is equivalent to Text="{Binding}".

OTHER TIPS

Like Anatoliy said you can't use a converter without a binding.

That's why a converter is used to convert the bound data if the bound data is updated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top