Silverlight 4.0 Silverlight转换器显示两位小数
我想在带有两个小数的文本框中显示一个小数。页面加载时,文本框中的值以两位小数(“0.00”)显示。当我将值改为10时,它只是显示为10。如何显示为“10.00” 下面是我的转换器Silverlight 4.0 Silverlight转换器显示两位小数,silverlight-4.0,decimal,ivalueconverter,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;
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);
}
提前感谢您不需要使用
值转换器
进行此操作,只需将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>
@StawWho我使用StringFormat='N2'尝试了相同的方法,但在加载页面时它只显示小数。当我将值更改为其他数字时,小数不显示。@感谢您的代码的人员。。但只需在文本框中手动输入5,就会失去焦点。。它仍然显示为5。我希望它显示为“5.00”。好吧,在文本被更改后,您并没有要求将文本框文本更改为包含两位小数。我的错。。我应该提一下。我想也许可以用别的方法。接受它作为答案。。谢谢:)
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));
}
}