Mateo Luis
Mateo Luis

Reputation: 1

How do I bind the RadiusX of a rectangle to the ActualHeight of the rectangle and multiply it by some number in Expression Blend 4 (or VS)?

Right now I am "cheating" and using the following:

<Rectangle x:Name="rectangle" Stroke="SlateGray" 
   Width="{TemplateBinding ActualWidth}" Height="{TemplateBinding ActualHeight}" 
   HorizontalAlignment="Stretch"  VerticalAlignment="Stretch"
   SizeChanged="rectangle_SizeChanged">
</Rectangle>

<x:Code>
  <![CDATA[ private void rectangle_SizeChanged(object sender, SizeChangedEventArgs e)
     {
        Rectangle r = sender as Rectangle;
        r.RadiusX = r.Height / 2;
        r.RadiusY = r.Height / 2;
     }
    ]]>
</x:Code>

This x:Code works perfectly at run time and accomplishes what I want. but I really want it to change instantly on the Artboard by doing something like:

<Rectangle x:Name="rectangle" Stroke="SlateGray" 
   Width="{TemplateBinding ActualWidth}" Height="{TemplateBinding ActualHeight}" 
   HorizontalAlignment="Stretch"  VerticalAlignment="Stretch"
   RadiusX=".5*({TemplateBinding ActualHeight})"
   RadiusY=".5*({TemplateBinding ActualHeight})"> 
</Rectangle>

But there is no way to include this .5*(...) Is there another way to accomplish this?

Upvotes: 0

Views: 303

Answers (1)

Walt Ritscher
Walt Ritscher

Reputation: 7047

To run code in a binding you use a converter class.

public class MultiplyConverter : IValueConverter 
{ 

  public double Multipler{ get; set; } 

  public object Convert(object value, Type targetType, 
         object parameter, System.Globalization.CultureInfo culture) 
    { 
        double candidate = (double)value; 
        return candidate * Multipler ;
    } 

  public object ConvertBack(object value, Type targetType, 
         object parameter, System.Globalization.CultureInfo culture) 
    { 

        throw new NotSupportedException(); 
    } 
} 

Then add the converter in a Resources section.

<Window.Resources>
    <local:MultiplyConverter x:Key="MultiplyConverter" Multipler="5"/>
</Window.Resources>

And add the coverter to your binding.

<Rectangle x:Name="rectangle" Fill="#FFA4A4E4"
        RadiusX="{Binding ActualHeight, Converter={StaticResource MultiplyConverter}, ElementName=rectangle}"
        RadiusY="{Binding ActualWidth, Converter={StaticResource MultiplyConverter}, ElementName=rectangle,}" />

You can use the Blend binding windows to automatically add the resource and binding.

Upvotes: 0

Related Questions