Reputation: 4885
I'm trying to simply do some Math on my custom control. I need to take a "Width" value and divide it by the Converter Paramater.
Here is the Binding:
<Border x:Name="circleBorder"
Grid.Row="0"
CornerRadius="{Binding Path=ActualWidth, ElementName=circleGrid}"
Width="{Binding Path=ActualWidth, ElementName=circleGrid}"
Height="{Binding Path=ActualWidth, ElementName=circleGrid}"
BorderBrush="White"
BorderThickness="{Binding Converter={StaticResource CalculateBorder}, Path=Width, ElementName=circleBorder, ConverterParameter=30}">
And this is the converter, which should do some simple Math.
public class CalculateBorder : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((double)value / (double)parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I'm getting this error on return ((double)value / (double)parameter);
:
Specified cast is not valid.
Upvotes: 1
Views: 4870
Reputation: 2702
The problem is that it is not possible to unbox parameter
because in this case parameter
is a string
.
The solution is converting the parameter to double with the Convert
class
var yourDouble = Convert.ToDouble(parameter);
The problem of the above code is that Convert
is defined as your Convert
method of the IValueConverter
. So you need to specify the full namespace by adding System
. The complete expression looks like this:
var yourDouble = System.Convert.ToDouble(parameter);
to make clear to the compiler that you want to use the System.Convert
class
Moreover the property BorderThickness
has the type Thickness
. so you should return a Thickness
object reference instead of a double
.
Upvotes: 8
Reputation: 2956
You have to return System.Windows.Thickness like below,
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return new Thickness(10,10,10,10);
}
The BorderThickness accepts System.Windows.Thickness
The converter parameter value
gives the object
of Thickness
class so you need to convert it to match your logic.
MSDN
public System.Windows.Thickness BorderThickness { get; set; }
Member of System.Windows.Controls.Border
Summary: Gets or sets the relative System.Windows.Thickness of a System.Windows.Controls.Border.
Returns: The System.Windows.Thickness that describes the width of the boundaries of the System.Windows.Controls.Border. This property has no default value.
Upvotes: 2
Reputation: 1293
object parameter is an string
return ((double)value / Convert.ToDouble(parameter));
Upvotes: 2