Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4273256
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T07:41:17+00:00 2026-05-21T07:41:17+00:00

I would like to have a TextBox that displays a number in currency format

  • 0

I would like to have a TextBox that displays a number in currency format (by setting StringFormat=c on the binding). When the TextBox is selected (when IsKeyboardFocused==true), I would like the formatting to go away, until the focus on the TextBox is lost.

I found a way to do this, code pasted below. My problem with this is that the binding is specified inside the Style – this means I have to retype the style for every TextBox I want to do this for. Idealy I would like to put the style somewhere central, and reuse it for every TextBox, with a different binding target for each.

Is there a way for me, using a Style, to set a parameter on the existing binding, something like Text.Binding.StringFormat="" ? (As opposed to setting the entire value of Text to a newly defined Binding)

Other suggestions to accomplish this would also be appreciated.

Code (this works, it’s just inconvenient):

<TextBox x:Name="ContractAmountTextBox">
<TextBox.Style>
    <Style TargetType="{x:Type TextBox}">                                       
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsKeyboardFocused, ElementName=ContractAmountTextBox}" Value="False">
                <Setter Property="Text" Value="{Binding Path=ContractAmount, UpdateSourceTrigger=LostFocus, StringFormat=c}"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding IsKeyboardFocused, ElementName=ContractAmountTextBox}" Value="True">
                <Setter Property="Text" Value="{Binding Path=ContractAmount, UpdateSourceTrigger=LostFocus}"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBox.Style>

  • 1 1 Answer
  • 3 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T07:41:18+00:00Added an answer on May 21, 2026 at 7:41 am

    It is feasible with an attached property, but it means you have to replace the binding entirely, then put it back.

    Here’s a quick and dirty implementation:

    public static class TextBoxBehavior
    {
    
        #region StringFormat
    
        public static string GetStringFormat(TextBox obj)
        {
            return (string)obj.GetValue(StringFormatProperty);
        }
    
        public static void SetStringFormat(TextBox obj, string value)
        {
            obj.SetValue(StringFormatProperty, value);
        }
    
    
        public static readonly DependencyProperty StringFormatProperty =
            DependencyProperty.RegisterAttached(
              "StringFormat",
              typeof(string),
              typeof(TextBoxBehavior),
              new UIPropertyMetadata(
                null,
                StringFormatChanged));
    
        // Used to store the original format
        private static readonly DependencyPropertyKey OriginalBindingPropertyKey =
            DependencyProperty.RegisterAttachedReadOnly(
                "OriginalBinding",
                typeof(BindingBase),
                typeof(TextBoxBehavior),
                new UIPropertyMetadata(null));
    
        private static void StringFormatChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            TextBox textBox = o as TextBox;
            if (textBox == null)
                return;
    
            string oldValue = (string)e.OldValue;
            string newValue = (string)e.NewValue;
    
            if (!string.IsNullOrEmpty(oldValue) && string.IsNullOrEmpty(newValue))
            {
                // Update target for current binding
                UpdateTextBindingSource(textBox);
    
                // Restore original binding
                var originalBinding = (BindingBase)textBox.GetValue(OriginalBindingPropertyKey.DependencyProperty);
                if (originalBinding != null)
                    BindingOperations.SetBinding(textBox, TextBox.TextProperty, originalBinding);
                textBox.SetValue(OriginalBindingPropertyKey, null);
            }
            else if (!string.IsNullOrEmpty(newValue) && string.IsNullOrEmpty(oldValue))
            {
                // Get current binding
                var originalBinding = BindingOperations.GetBinding(textBox, TextBox.TextProperty);
                if (originalBinding != null)
                {
                    // Update target for current binding
                    UpdateTextBindingSource(textBox);
    
                    // Create new binding
                    var newBinding = CloneBinding(originalBinding);
                    newBinding.StringFormat = newValue;
    
                    // Assign new binding
                    BindingOperations.SetBinding(textBox, TextBox.TextProperty, newBinding);
    
                    // Store original binding
                    textBox.SetValue(OriginalBindingPropertyKey, originalBinding);
                }
            }
        }
    
        private static void UpdateTextBindingSource(TextBox textBox)
        {
            var expr = textBox.GetBindingExpression(TextBox.TextProperty);
            if (expr != null &&
                expr.ParentBinding != null &&
                (expr.ParentBinding.Mode == BindingMode.Default // Text binds two-way by default
                || expr.ParentBinding.Mode == BindingMode.TwoWay
                || expr.ParentBinding.Mode == BindingMode.OneWayToSource))
            {
                expr.UpdateSource();
            }
        }
    
        private static Binding CloneBinding(Binding original)
        {
            var copy = new Binding
                             {
                                 Path = original.Path,
                                 XPath = original.XPath,
                                 Mode = original.Mode,
                                 Converter = original.Converter,
                                 ConverterCulture = original.ConverterCulture,
                                 ConverterParameter = original.ConverterParameter,
                                 FallbackValue = original.FallbackValue,
                                 TargetNullValue = original.TargetNullValue,
                                 NotifyOnSourceUpdated = original.NotifyOnSourceUpdated,
                                 NotifyOnTargetUpdated = original.NotifyOnTargetUpdated,
                                 NotifyOnValidationError = original.NotifyOnValidationError,
                                 UpdateSourceExceptionFilter = original.UpdateSourceExceptionFilter,
                                 UpdateSourceTrigger = original.UpdateSourceTrigger,
                                 ValidatesOnDataErrors = original.ValidatesOnDataErrors,
                                 ValidatesOnExceptions = original.ValidatesOnExceptions,
                                 BindingGroupName = original.BindingGroupName,
                                 BindsDirectlyToSource = original.BindsDirectlyToSource,
                                 AsyncState = original.AsyncState,
                                 IsAsync = original.IsAsync,
                                 StringFormat = original.StringFormat
                             };
    
            if (original.Source != null)
                copy.Source = original.Source;
            if (original.RelativeSource != null)
                copy.RelativeSource = original.RelativeSource;
            if (original.ElementName != null)
                copy.ElementName = original.ElementName;
    
            foreach (var rule in original.ValidationRules)
            {
                copy.ValidationRules.Add(rule);
            }
            return copy;
        }
    
        #endregion
    }
    

    Usage:

    <TextBox x:Name="ContractAmountTextBox"
             Text="{Binding Path=ContractAmount, UpdateSourceTrigger=LostFocus, StringFormat=c}">
        <TextBox.Style>
            <Style TargetType="{x:Type TextBox}">                                       
                <Style.Triggers>
                    <Trigger Property="IsKeyboardFocused" Value="True">
                        <Setter Property="local:TextBoxBehavior.StringFormat" Value="N"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>
    

    Using this, you can also reuse the style for different TextBoxes

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to have a TextBox that supports AutoComplete and lets users type
I have a textbox that I would like for only numbers. But if I
I have a WPF screen that displays a number of TextBox inputs. I have
I would like to have direct access to the text inside a textbox on
I have a asp:GridView which contains a asp:TextBox within a TemplateField. I would like
So in my project i would like have a nice treeview that has images.
I would like to have an AppWidget that designed like this one . Image:
I have the following code. This displays data in following format H:M:S. I would
I have a report that I would like to display with some data hidden
I have successfully created a textbox that displays / collapses an error message depending

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.