3

Is there a way to bind a decimal to a WPF TextBox and specify a StringFormat (in this case Currency)? I've tried doing this with a property in the View Model, but editing in the TextBox becomes a little quirky as it tries to apply the formatting after every keystroke:

public string Moneys
{
    get
    {
        return string.Format("{0:C}", Model.Moneys);
    }

    set
    {
        if ( decimal.TryParse(value, NumberStyles.Currency, null, out decimal decimalValue) )
        {
            Model.Moneys = decimalValue;
        }
    }
}

I tried setting the DataContext and used Xaml data binding instead. Xaml:

<TextBox Text="{Binding Path=Moneys, StringFormat=C0}" />

Code behind:

this.WhenAnyValue(x => x.ViewModel.Model)
    .Subscribe(x =>
   {
       DataContext = x;
   });

However, after changing DataContext the {Binding} does not change as I'd expected to.

Is there a way to use this.Bind and specify the StringFormat? for me, that would be the ideal solution

UPDATE

In the case of setting the DataContext, I realised that I should just be assigning it to the ViewModel and when ViewModel.Model changes, the template reflects the changes as it should. Here's my updated xaml:

<TextBox Text="{Binding Path=Model.Moneys, StringFormat=C0}" />

However, I would still like to know if you can set the StringFormat in the code behind using ReactiveUI.

Mitkins
  • 4,031
  • 3
  • 40
  • 77

1 Answers1

3

You can use an inline Binding Converter, do the bind in the code behind (your textbox will need a name):

this.Bind(
    ViewModel, 
    x => x.ViewModel.Model.Moneys, 
    x => x.nameOfTheTextbox,
    x => ConvertToText(x),
    x => ConvertToDec(x));

And the methods:

private string ConvertToText(decimal value)
{
    return string.Format("{0:C}", value);
}

private decimal ConvertToDec(string value)
{
    decimal result;
    if (!decimal.TryParse(value, NumberStyles.Currency, null, out result))       
    {
        result = 0;
    }
    return result
}
Luis
  • 436
  • 4
  • 11