2013-05-30 43 views
0

我一直在尋找一種處理百分比的好方法。在我們的應用程序中,我們需要顯示和編輯百分比值,並使用不同的小數位數,即當用戶當前沒有關注文本框時,應顯示12.50%,但編輯該值時應顯示爲0.12501015512312311。更糟糕的是,用戶應該能夠選擇在運行時顯示的小數位數。此外,用戶應該被允許輸入12.5%,這將轉化爲0.125。我知道我可以用轉換器做到這一點,但是我將所有這些要求合併爲一個體面的解決方案時遇到了麻煩。如何處理WPF中的百分比輸入和顯示?

這是我最好的嘗試迄今:

public class PercentConverter : IValueConverter 
{ 
    private static int numberOfDecimals = CultureInfo.CurrentCulture.NumberFormat.PercentDecimalDigits; 
    public static int NumberOfDecimals 
    { 
     get { return numberOfDecimals; } 
     set 
     { 
      if(value != numberOfDecimals) 
      { 
       numberOfDecimals = value; 
      } 
     } 
    } 

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     decimal pct = System.Convert.ToDecimal(value); 
     CultureInfo ci = new CultureInfo(CultureInfo.CurrentCulture.Name, false); 
     ci.NumberFormat.PercentDecimalDigits = NumberOfDecimals; 
     return String.Format(ci, "{0:P}", pct); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     string percentString = value as string; 
     string doubleString = percentString.TrimEnd(culture.NumberFormat.PercentSymbol.ToCharArray()); 
     double percent = Double.Parse(doubleString, NumberStyles.Any); 

     if (IsExplicitPercentage(percentString, culture)) 
     { 
      percent /= 100; 
     } 

     return percent; 
    } 

    private bool IsExplicitPercentage(string percentString, CultureInfo culture) 
    { 
     return percentString.Contains(culture.NumberFormat.PercentSymbol); 
    } 
} 

,然後在XAML

<DataGrid.Columns> 
      <DataGridTextColumn Header="Beskrivelse" Binding="{Binding Description}" /> 
      <DataGridTemplateColumn Header="Share"> 
       <DataGridTemplateColumn.CellTemplate> 
        <DataTemplate> 
         <TextBox HorizontalContentAlignment="Right" HorizontalAlignment="Stretch"> 
          <TextBox.Style> 
           <Style TargetType="{x:Type TextBox}"> 
            <!-- Other Style Setters --> 
            <Setter Property="Text" Value="{Binding Share, Converter={StaticResource pctConverter}}" /> 
            <Style.Triggers> 
             <Trigger Property="IsKeyboardFocused" Value="True"> 
              <Setter Property="Text" Value="{Binding Share}" /> 
             </Trigger> 
            </Style.Triggers> 
           </Style> 
          </TextBox.Style> 
         </TextBox> 
        </DataTemplate> 
       </DataGridTemplateColumn.CellTemplate> 
      </DataGridTemplateColumn> 
     </DataGrid.Columns> 

但是這不會正確綁定到datacontex,當我在文本框中更改值,它不會更新它綁定到的模型的屬性。

請注意,我對WPF來說很新,所以我可能會缺少一些基本的東西。

回答

0

您需要修改爲Text屬性的綁定:

<Setter Property="Text" Value="{Binding Share, Converter={StaticResource pctConverter}, UpdateSourceTrigger=PropertyChanged}" /> 

這將導致DataContext對象的屬性值來改變每個字符鍵入。默認情況下,該屬性在該字段失去焦點後發生更改。

+0

其實我很好地更新LostFocus,但它沒有工作,直到我明確將UpdateSourceTrigger設置爲綁定中的LostFocus。奇怪......謝謝;) –