Giacomo Tagliabue
Giacomo Tagliabue

Reputation: 1759

Excel-like behavior WPF textbox

I want to create a textbox which text binds an integer (e.g 123456789), but it shows the thousand separator (eg 123.456.789), but when I select the textbox for editing it the string returns without separator, until the textbox loses the focus, just like in Excel. Any advice?

Upvotes: 1

Views: 1166

Answers (2)

fixagon
fixagon

Reputation: 5566

one possibility:

you add a style which creates a trigger on IsFocused. in the trigger you set a new template in which you have another formatting:

<Grid>
  <Grid.Resources>
    <System:Double x:Key="boundDouble">1000</System:Double>
    <System:Double x:Key="boundDouble2">2000</System:Double>
  </Grid.Resources>
  <TextBox Width="100" Height="30">
    <TextBox.Text>
      <Binding Source="{StaticResource boundDouble}" Path="." StringFormat="{}{0:F3}" />
    </TextBox.Text>
    <TextBox.Style>
      <Style TargetType="TextBox">
        <Style.Triggers>
          <Trigger Property="IsFocused" Value="true">
            <Setter Property="Template">
              <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                  <TextBox>
                  <TextBox.Text>
                    <Binding Source="{StaticResource boundDouble}" Path="." StringFormat="{}{0:F5}" />
                  </TextBox.Text>
                  </TextBox>
                </ControlTemplate>
              </Setter.Value>
            </Setter>
          </Trigger>
        </Style.Triggers>
      </Style>
    </TextBox.Style>
  </TextBox>
</Grid>

Upvotes: 0

Rachel
Rachel

Reputation: 132618

Use a Trigger which formats the value if the TextBox isn't selected

<Style TargetType="{x:Type TextBox}">
    <Setter Property="Text" Value="{Binding SomeValue, StringFormat=N2}" />
    <Style.Triggers>
        <Trigger Property="IsKeyboardFocusWithin" Value="True">
            <Setter Property="Text" Value="{Binding SomeValue}" />
        </Trigger>
    </Style.Triggers>
</Style>

You can also use a Converter for formatting if you can't easily format with StringFormat

Upvotes: 2

Related Questions