类似excel的行为wpf文本框

时间:2011-12-30 14:43:34

标签: c# wpf

我想创建文本框绑定整数的文本框(例如123456789),但它显示千位分隔符(例如123.456.789),但是当我选择文本框进行编辑时,字符串返回时不带分隔符,直到文本框丢失焦点,就像在excel中一样。有什么建议?谢谢!

2 个答案:

答案 0 :(得分:2)

使用触发器,如果​​未选择TextBox,则格式化值

<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>

如果无法使用StringFormat

轻松格式化,也可以使用Converter进行格式化

答案 1 :(得分:0)

一种可能性:

添加一个在IsFocused上创建触发器的样式。 在触发器中,您可以设置一个新模板,在该模板中有另一种格式:

<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>