Creé un convertidor para convertir de doble a entero.¿Por qué mi convertidor genera un error de conversión no válido?
Pero la línea "return (int) value;" siempre obtiene un "yeso especificado no es válido".
¿Qué debo hacer para que mi convertidor convierta con éxito un doble y devuelva un número entero?
Convertidor:
namespace TestChangeAngle
{
[ValueConversion(typeof(double), typeof(int))]
class DoubleToIntegerConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (int)value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
XAML:
<Page x:Class="TestChangeAngle.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestChangeAngle"
Title="Page1">
<Page.Resources>
<local:DoubleToIntegerConverter x:Key="DoubleToIntegerConverter"/>
</Page.Resources>
<StackPanel HorizontalAlignment="Left" Margin="20">
<Image Source="images\logo2.png"
RenderTransformOrigin="0.5, 0.5"
Width="100"
Margin="10">
<Image.RenderTransform>
<RotateTransform Angle="{Binding ElementName=TheSlider, Path=Value}"/>
</Image.RenderTransform>
</Image>
<Slider x:Name="TheSlider"
Width="200"
Minimum="0"
Maximum="360"
HorizontalAlignment="Center"
Margin="10"
Cursor="Hand"/>
<TextBox x:Name="TheAngle"
Margin="10"
Width="100">
<TextBox.Text>
<Binding ElementName="TheSlider"
Path="Value"
UpdateSourceTrigger="PropertyChanged"
Converter="{StaticResource DoubleToIntegerConverter}"
Mode="TwoWay">
<Binding.ValidationRules>
<local:MinMaxValidationRule Minimum="0" Maximum="360"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</StackPanel>
</Page>
Si el parámetro es siempre un valor doble que return (int) (double); también funcionará, pero ToInt32 es mejor. – Nir
@Nir - sí, esto permitiría al compilador hacer una conversión implícita de doble a int aunque parezca un reparto. – tvanfosson