2016-11-18 125 views
0

我想进行转换,将Decimal转换为Int。看看我的代码:十进制到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,并使进度条最终工作。

+1

你能告诉你的'DeciamlToInt'转换器? – Romasz

+0

您的转换器需要通过储蓄目标以及余额。 IValueConverter接口确实指定了一个参数,但增加一个“派生属性”来计算,可能会更直截了当。类似于'public int PercentOfGoal {get {return(int)(Balance/SavingsGoal)* 100; }}',然后将'Value'绑定到那个。 –

+0

在我的转换器上没有任何东西的时候。现在我在Convert方法中做了这样的事情: 'if(value is decimal){ return System.Convert.ToInt32(value); } return false;' –

回答

3

你是否真的需要小数? Maximum属性和Value属性是双打的,所以如果这个项目是关于金钱的,只需使用double。如果逗号后不需要16位以上的数字,双精度就会更高。

如果你还是想用转换器转换转换的转换() - 你的转换器的方法类

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

哦,谢谢!我会改变它加倍! –

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? 
    } 
} 
+0

我已经将我的Converter注册为静态资源。谢谢! :) –

0

你要截断或圆形的小数?如果你确定四舍五入, 你不需要一个转换器。你可以在绑定中使用StringFormat参数。如果你使用#的字符串格式,它会轮到。

+0

我试过它与StringFormat参数,但它没有在我的情况下工作,由于我的代码中的其他问题。 –

0

是更好首先检查它是否真的十进制?我的意思是类似的东西:

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