Rafael A. M. S.
Rafael A. M. S.

Reputation: 637

StringFormat not working on TextBox

I'm trying to make a currency formatted textbox but it's not working.

XAML:

<TextBox x:Name="_valueTxt" Text="{Binding Amount, StringFormat={}{0:C}}"/>

Code Behind:

...
string _amount;
public string Amount
{
    get { return _amount; }
    set { _amount = value; }
}
...
public MyWindow()
{
    Amount = "1235533";
    InitializeComponent();
}

Value I expect to see in my textbox:

$1.235.533,00

But it's showing:

1235533

Upvotes: 3

Views: 3752

Answers (2)

Dirty Coder
Dirty Coder

Reputation: 114

internal class MyClass
{
    private double amount = 1209382;

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

internal class Program
{
    private static void Main(string[] args)
    {

        MyClass instance = new MyClass();
        Console.WriteLine(instance.Amount);

        Console.ReadKey();
    }
}

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

You can only use StringFormat with numerical format strings if you're binding to a number. Your Amount property is already a string, so you will get it as-is.

If you change the Amount property to be a numerical value, you will get what you expect, ie:

double _amount;
public double Amount
{
    get { return _amount; }
    set { _amount = value; }
}
...
public MyWindow()
{
    Amount = 1235533;
    InitializeComponent();
}

Note that you may also want to make Amount either a DependencyProperty or have it implement INotifyPropertyChanged. This will allow changes to the value to be reflected in the user interface.

Upvotes: 6

Related Questions