1

我想在带有两位小数的文本框中显示一个小数。当页面加载时,文本框中的值显示为两位小数 ("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);
    }

提前致谢

4

1 回答 1

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));
    }
}
于 2013-03-15T12:48:21.983 回答