2011-12-30 49 views
1

我想創建一個至少包含一個整數(例如123456789)的文本框,但它顯示了千位分隔符(例如123.456.789),但是當我選擇文本框進行編輯時,字符串返回時沒有直到文本框失去焦點,就像在Excel中一樣。有什麼建議?謝謝!excel-like wpf textbox

回答

2

使用觸發器如果文本框沒有選擇

<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格式格式化值

+0

謝謝,完美的作品!只有一件事,你知道我如何將千位分隔符從「,」改爲「」。直接在xaml setter表達式中? StackOverFlow社區,你真棒:) – 2011-12-30 15:30:55

+0

@GiacomoTagliabue你可能不得不使用'Converter'來代替'StringFormat'。只需格式化爲正常格式即可。'替換()'帶點的逗號 – Rachel 2011-12-30 15:34:02

+0

謝謝,我不想使用'Converter',但在這種情況下它似乎是唯一的可能性 – 2011-12-30 15:37:06

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>