Search code examples
c#wpfivalueconverter

IValueConverter parameter for conditional converting


I have a form with text boxes that take (by default) a decimal value. Unfortunately, business rules say they can also take a percentage value (effectively the same thing, just multiplied by 100). To make sure the correct value is inserted to the db (eg if the respondent has input 95, I want it to become .95), I have added Checkboxes next to the relevant TextBoxes which the user can select to indicate that the value is a percentage, not a decimal. To switch the values between decimal and percent for future display, reporting etc, I am trying to use an IValueConverter.

I have created a converter that multiplies the field value to display it as a percentage, and (though I haven't gotten to testing yet) should re-convert that display value back to a decimal on saving.

The problem i have is getting the converter to only work where the Checkboxes are selected. From all my reading it seems the most likely way to do this would be to use the checkbox value as the parameter to the IValueConverter, but I have no idea how to do this.

So, my question is: How do I (or even can I) use the Checkbox.IsChecked value from the Checkbox sitting next to the TextBox as the parameter to the IValueConverter to determine or not whether to do a conversion on the TextBox text? The issue is how to identify the Checkbox that relates to the TextBox being converted and how to pass its value as the IValueConverter's parameter

I tried loolking here: How can I pass a reference to another control as an IValueConverter parameter?, but it got a bit depressing.

Thanks in advance.


Solution

  • Unfortunately, you can't use a Binding on the ConverterParameter, but you could use an IMultiValueConverter for this task.

    You'd use it like

    <TextBlock.Text>
      <MultiBinding Converter="{StaticResource YourConverter}">
        <Binding Path="YourDecimalProperty"/>
        <Binding Path="IsChecked" ElementName="YourCheckBoxName" />
      </MultiBinding>
    </TextBlock.Text>