Search code examples
c#wpfxamldata-bindingvalueconverter

Apply value converter in XAML without databinding


I have a TextBlock in my view that I want to always display the number 1, converted into the local currency. (e.g. $1 in US, £1 in UK, etc). I have a value converter that can do this, but I don't know how to apply a value converter to the value of 1 without getting my data from a databinding.

I can think of two solutions, but they each have their problems, and I'm looking for something more elegant:

  1. Create a property on my ViewModel that just holds and returns the value 1 and bind to it. Then add my converter to this binding. This seems backwards, particularly as this is view-only code.

  2. Make a binding point to an existing property and modify my converter to ignore the value given to it, and instead use the parameter to give it the number 1. This feels unintuitive to other programmers, as they'll be confused as to why I'm binding to a different property there.

Is there some way of applying a converter without first creating a binding?


Solution

  • If you want for this to be relatively readable from XAML alone, you can always do it like this:

    <Label>
       <Label.Resources>
          <system:Int32 x:Key="defaultValue">1</system:Int32>
       </Label.Resources>
       <Label.Content>
          <Binding Source="{StaticResource defaultValue}"
                Converter="{StaticResource CurrencyConverter}" />
       </Label.Content>
    </Label>