2013-03-15 53 views
1

我想在帶兩位小數的文本框中顯示小數點。當頁面加載文本框中的值時顯示兩位小數(「0.00」)。當我將數值改爲10時,它僅顯示爲10.我如何顯示它爲「10.00」Silverlight轉換器顯示兩位小數點

以下是我的轉換器。

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 

     decimal convertedBudget; 
     if (value == null) 
     { 
      convertedBudget = 0.0M; 
     } 
     else 
     { 
      convertedBudget = (decimal)value; 
     } 
     return string.Format("{0:#,0.00}", Math.Round(convertedBudget, 2)); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     decimal convertedBudget = 0; 
     if(value!=null && !string.IsNullOrEmpty(value.ToString())) 
     { 
      convertedBudget = System.Convert.ToDecimal(value.ToString()); 
     } 
     return Math.Round(convertedBudget, 2); 
    } 

在此先感謝

回答

0

你不需要ValueConverter此,只要綁定TextBox.Textdecimal和使用字符串在TextBox本身的格式。 如果您想在輸入文字後更新數值,請捕捉適當的事件並進行更改。

<UserControl x:Class="SilverlightApplication2.MainPage" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d" 
d:DesignHeight="300" d:DesignWidth="400" 
xmlns:local="clr-namespace:SilverlightApplication2"> 
<UserControl.DataContext> 
    <local:VM x:Name="VM"/> 
</UserControl.DataContext> 
    <Grid x:Name="LayoutRoot" Background="White"> 
    <TextBox Text="{Binding MyValue, Mode=TwoWay, StringFormat=\{0:0.00\}}" LostFocus="TextBox_LostFocus_1" /> 
    <Slider HorizontalAlignment="Left" Margin="75,189,0,0" VerticalAlignment="Top" Value="{Binding MyValue, Mode=TwoWay}" Width="293"/> 
</Grid> 


public partial class MainPage : UserControl 
{ 
    public MainPage() 
    { 
     InitializeComponent(); 
    } 

    private void TextBox_LostFocus_1(object sender, RoutedEventArgs e) 
    { 
     var v = (VM)this.DataContext; 
     v.MyValue = Convert.ToDecimal(((TextBox)sender).Text); 
    } 
} 

public class VM : INotifyPropertyChanged 
{ 
    public VM() 
    { 

    } 

    private decimal myValue; 
    public decimal MyValue 
    { 
     get { return myValue; } 
     set { myValue = value; OnChanged("MyValue"); } 
    } 


    public event PropertyChangedEventHandler PropertyChanged; 
    private void OnChanged(string pName) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(pName)); 
    } 
} 
+0

@StawWho我試圖用相同的StringFormat = 'N2',但加載頁面時,它只是顯示小數。當我將該值更改爲其他數字時,小數點不顯示。 – Shrikey 2013-03-15 12:53:45

+0

更新完整的工作示例 – StaWho 2013-03-15 13:06:33

+0

@Stawwho欣賞你的代碼..但只是在文本框中手動輸入5並失去其焦點。它仍然顯示爲5.我希望顯示爲「5.00」。 – Shrikey 2013-03-15 13:16:08

相關問題