十进制到Int转换器

时间:2016-11-18 18:23:08

标签: c# uwp

我想进行转换,将Decimal转换为Int。看看我的代码:

<ProgressBar Margin="0,10,0,10" 
    Grid.Row="2" Grid.ColumnSpan="3" IsIndeterminate="False" Height="10"
    Maximum="{Binding SavingGoal, Converter={StaticResource DecimalToInt}}" Value="{Binding Balance, Converter={StaticResource DecimalToInt}}"/>

这就是绑定指向的地方:

newGoal.SavingGoal = Convert.ToDecimal(SavingsAmountsTextBox.Text);
newGoal.Balance = 0;

这是班级:

public decimal SavingGoal { get; set; }
public decimal Balance { get; set; }

所以我的问题是我不知道如何使用IValueConverter来适应我的情况。我想将我的UserControl正在解析的小数转换为int,并使进度条最终起作用。

4 个答案:

答案 0 :(得分:3)

你真的需要小数吗? Maximum属性和Value属性是双倍的,所以如果这个项目是钱,只需使用double。如果您在逗号后不需要超过16位数字,则双倍更有效。

如果您仍想使用转换器转换它,请转换为Convert() - 转换器类的方法

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    decimal x = (decimal)value;
    return Decimal.ToInt32(x);
}

答案 1 :(得分:1)

您必须将DecimalToInt转换器注册为静态资源

<ns:DecimalToIntConverter x:Key="DecimalToInt" />

然后实施

public class DecimalToIntConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // convert here
        // value is your binding - use it if you can
        // parameter is the additional parameter that you can pass in but don't need to.
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value; // who cares?
    }
}

答案 2 :(得分:0)

你想要截断或舍入小数?如果你没有四舍五入, 你不需要转换器。您可以使用绑定上的StringFormat参数来执行此操作。如果你使用#的字符串格式,它将会循环。

答案 3 :(得分:0)

首先检查它是否真的是小数?我的意思是这样的:

if (value is decimal){ return System.Convert.toInt32(value); } return false;