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

  • Home
  • SEARCH
  • 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 8403541
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T22:22:17+00:00 2026-06-09T22:22:17+00:00

What I want to do is simple, show one formatting when a TextBox has

  • 0

What I want to do is simple, show one formatting when a TextBox has focus and another when it doesn’t. In my case I’m rounding a number to 3 digits when not focused but showing the actual, entire number when focused for editing.

I have a fairly simple solution using a multibinding and I feel like I’m almost there. Everything works as expected and there are no errors in the immediate window, but the binding won’t update the source.

I’m using this style to pass my binding and whether or not the TextBox has focus to the converter.

<Style x:Key="RoundedTextBox" TargetType="{x:Type ContentControl}">
    <Setter Property="Focusable" Value="False"/>
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBox x:Name="TB" TextAlignment="Right" DataContext="{TemplateBinding Content}">
                    <TextBox.Text>
                        <MultiBinding Converter="{StaticResource DecRounder}" UpdateSourceTrigger="PropertyChanged">
                            <MultiBinding.Bindings>
                                <Binding ElementName="TB" Path="DataContext" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" BindsDirectlyToSource="True" />
                                <Binding ElementName="TB" Path="IsFocused" Mode="OneWay" />
                            </MultiBinding.Bindings>
                        </MultiBinding>
                    </TextBox.Text>
                </TextBox>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

Example usage:

<ContentControl Style="{StaticResource RoundedTextBox}"
                Content="{Binding Path=Model.SomeNumber}" />

And the multi-value converter is here.

public class DecimalRoundingConverter : IMultiValueConverter
{

    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {

        if (values.Length != 2)
            throw new Exception("Invalid number of values for DecimalRoundingConverter!");

        if (values[0] is string)
            return values[0];

        if (values[0] != null && !(values[0] is decimal))
            throw new Exception("Invalid type for first value used with DecimalRoundingConverter!");
        if (!(values[1] is bool))
            throw new Exception("Invalid type for second value used with DecimalRoundingConverter!");
        if (targetType != typeof(string))
            throw new Exception("Invalid target type used with DecimalRoundingConverter!");

        if (values[0] == null)
            return null;

        decimal number = (decimal)values[0];

        bool isFocused;
        if (values[1] == null)
            isFocused = true;
        else if (values[1] is bool)
            isFocused = (bool)values[1];
        else
            if (!bool.TryParse((string)values[1], out isFocused))
                throw new Exception("Invalid converter parameter used with DecimalRoundingConverter!");

        return string.Format(isFocused ? "{0:.#############################}" : "{0:.###}", number);

    }

    public object[] ConvertBack(object value, Type[] targetType, object parameter, System.Globalization.CultureInfo culture)
    {

        decimal d;
        var ret = new object[2];

        if (value == null)
            ret[0] = null;
        else if (decimal.TryParse((string)value, out d))
            ret[0] = d;
        else
            ret[0] = value;

        ret[1] = Binding.DoNothing;

        return ret;

    }

}
  • 1 1 Answer
  • 0 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-06-09T22:22:19+00:00Added an answer on June 9, 2026 at 10:22 pm

    For what it’s worth, I derived a solution from this CodeProject article. The key is using a Trigger in the style to switch the content template. The provided example isn’t perfect, but it was a good learning experience.

    The only drawback to this approach is that the ContentTemplates and Style must be defined in the UserControl since the ContentTemplates refer directly to TextBox event handlers. This is because the reference to the TextBox must be passed to the code behind. When you try to override the style you’ll lose the trigger that switches ContentTemplate.

    This drawback was fine for me since I’m binding to an application setting for important properties, like ContentStringFormat.

    EDIT

    Here’s a better method in full XAML. I wrote up a corresponding article on my blog.

    <ControlTemplate x:Key="EditableDecimalTemplate" TargetType="{x:Type ContentControl}">
        <ContentPresenter Name="contentHolder" 
                                VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                RecognizesAccessKey="True" 
                                SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}">
            <ContentPresenter.Content>
                <Grid Margin="0">
                    <Border Name="nonFocusedBorder"
                            Grid.ZIndex="3" IsHitTestVisible="False"
                            BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" 
                            Background="{TemplateBinding Background}" 
                            />
                    <TextBox Name="editTextBox"
                                Grid.ZIndex="1" Opacity="0"
                                Margin="0" Padding="{TemplateBinding Padding}"
                                HorizontalAlignment="Stretch" VerticalAlignment="Center"
                                TextAlignment="Right"
                                Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content, Mode=TwoWay}"
                                BorderThickness="{TemplateBinding BorderThickness}" 
                                />
                    <Border BorderBrush="{x:Null}" Height="{Binding ElementName=editTextBox, Path=ActualHeight}" Margin="0,0,3,0"
                            Padding="{TemplateBinding BorderThickness}">
                        <TextBlock Name="displayTextBlock" 
                                    Grid.ZIndex="2" IsHitTestVisible="False"
                                    VerticalAlignment="Center" HorizontalAlignment="Stretch" 
                                    Margin="{TemplateBinding Padding}"
                                    TextAlignment="Right"
                                    Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content, StringFormat={}{0:#.###;-#.###;0}, Mode=OneWay}"
                                    />
                    </Border>
                    <Border/>
                </Grid>
            </ContentPresenter.Content>
        </ContentPresenter>
        <ControlTemplate.Triggers>
            <Trigger SourceName="editTextBox" Property="IsKeyboardFocused" Value="True">
                <Setter TargetName="displayTextBlock" Property="Opacity" Value="0" />
                <Setter TargetName="editTextBox" Property="Opacity" Value="1" />
                <Setter TargetName="nonFocusedBorder" Property="Visibility" Value="Collapsed"/>
            </Trigger>
            <Trigger Property="BorderThickness" Value="0">
                <Setter TargetName="editTextBox" Property="BorderThickness" Value="1" />
                <Setter TargetName="nonFocusedBorder" Property="BorderThickness" Value="1" />
                <Setter TargetName="nonFocusedBorder" Property="BorderBrush" Value="Transparent" />
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
    
    <Style x:Key="EditableDecimalLabel" TargetType="{x:Type Label}">
        <Setter Property="Template" Value="{StaticResource EditableDecimalTemplate}" />
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="VerticalContentAlignment" Value="Stretch"/>
        <Setter Property="Padding" Value="4" />
        <Setter Property="FontFamily" Value="Consolas, Lucida Console, Courier New"/>
        <Setter Property="TextElement.FontSize" Value="13" />
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="BorderThickness" Value="1" />
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="BorderBrush" Value="#B5CFFF"/>
            </Trigger>
        </Style.Triggers>
    </Style>
    

    And sample usage:

    <Label Name="TestControl"
           Width="120"
           Content="{Binding Path=MyNumber, Mode=TwoWay}"
           Style="{StaticResource EditableDecimalLabel}"
           />
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is another simple 'matrix' question in Mathematica. I want to show how I
I want to show some bold and some simple word within the same sentence.If
I want to create a simple multiline Alert popup Alert.show(Blah\\nBlah) shows Blah\nBlah when what
I want to show all PDF filenames that has 33 in any position. sample
I want a simple form with one text box and a submit button. For
I want to create one simple application for sending request from iphone(client) by using
I'm kind of stuck with one - presumably simple to resolve problem. I want
This is a really simple one but it's driving me crazy. I want to
My question is simple, i want to show a dialog with an animated circle
I have made a simple form with one textField and command, I want to

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.