我想在包含两个小数的文本框中显示一个小数。当页面加载时,文本框中的值显示为两个小数("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);
}
Thanks in advance
您不需要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));
}
}