Silverlight转换器显示两个位置的小数

时间:2013-03-15 12:27:07

标签: silverlight-4.0 decimal ivalueconverter

我想在带有两位小数的文本框中显示小数。页面加载时,文本框中的值显示为两位小数(“0.00”)。当我将值更改为10时,它只显示为10.如何将其显示为“10.00”

以下是我的转换器。

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);
    }

提前致谢

1 个答案:

答案 0 :(得分:0)

您不需要ValueConverter,只需将TextBox.Text绑定到decimal并在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));
    }
}