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
.