0
votes

I created public void that formating all the textbox in grid to currency

My code

public void FormatinTextBox()
    {
        foreach (Control ctrl in MainGrid.Children)
        {
            if (ctrl.GetType() == typeof(TextBox))
            {
                double amount = 0.0d;
                if (Double.TryParse(((TextBox)ctrl).Text, NumberStyles.Currency, null, out amount))
                    ((TextBox)ctrl).Text = amount.ToString("C");
                else
                    ((TextBox)ctrl).Text = String.Empty;
            }
        }
    }

and it's working perfect if i put this code to event handler of MainGrid_Loaded.

but i want to run this code for each time i leave textbox (lostFocus).

i prefer to fire this code with xaml on each textbox, i dont know if it possible to do that. this is my code in xaml for one of my textbox

<TextBox x:Name="Nose" HorizontalAlignment="Left" Height="24" Margin="710,209,0,0" TextWrapping="Wrap"                  
                     VerticalAlignment="Top" Width="110" BorderThickness="0,0,0,1" Text="100" LostFocus="Nose_LostFocus"/>

if it's not possible, how can i run this code on back code

private void Nose_LostFocus(object sender, RoutedEventArgs e)
{

}
1
StringFormat='{}{0:c}' on your TextBox? that way you don't need any backend code trying to format it.user9401448
can you please describe how and where to put it?Idan Sim
@IdanSim I need to do similar in Winform. did you find a solution to this?amindomeniko

1 Answers

0
votes

If you bind the Text property to a source property, you could apply a StringFormat to the binding:

public partial class MainWindow : Window
{
    public MainWindow ()
    {
        InitializeComponent();
        Nose.DataContext = this;
    }

    public decimal? Text { get; set; }
}

XAML:

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

But if you wan't some custom logic, you could use an event handler. You would implement it pretty much the same way as you did before:

private void Nose_LostFocus(object sender, RoutedEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    double amount;
    textBox.Text = (double.TryParse(textBox.Text, out amount)) ? amount.ToString("C") : string.Empty;
}