tags:

views:

130

answers:

2

As an example, if I have an element whose size I want to be twice the size of another element, how would I achieve this?

An example would be the following, mirroredObject is the object that I want to use half of it's width for the width of the Border object.

<Border Width="{Binding ActualWidth, ElementName=mirroredObject, Mode=Default}" />

I have other situations where the property I might like to bind to might be the sum of the widths of other elements, how would I achieve this also?

SOLUTION

Please refer to my answer for the solution which was aided by lenanovd's answer.

+4  A: 

You can use binding converter that convert int to another int using your formula. For example of binding converter please read this article.

Hope it helps.

levanovd
Fantastic, thanks for that levanovd, I've just created a converter and will add a solution to my question in case others wish to bind to other interface elements.
Brett Ryan
+1  A: 

Thanks to levanovd for providing a hint on how to solve this problem. Following is my solution to this problem, thanks again levanovd.

Create a converter

[ValueConversion(typeof(double), typeof(double))]
public class MultiplierConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        if (targetType != typeof(Double))
            throw new Exception("Conversion not allowed.");
        double f, m = (double)value;
        string par = parameter as string;
        if (par == null || !Double.TryParse(par, out f)) f = 1;
        return m * f;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        if (targetType != typeof(Double))
            throw new Exception("Conversion not allowed.");
        double f, m = (double)value;
        string par = parameter as string;
        if (par == null || !Double.TryParse(par, out f)) f = 1;
        return f == 0 ? float.NaN : m / f;
    }
}

Add converter to your XAML

<Window.Resources>
  <n:MultiplierConverter x:Key="MultiplierConverter"/>
</Window.Resources>

Add binding between objects specifying argument for multiplier.

<StackPanel>
  <Rectangle x:Name="source" Width="100" Height="100" Stroke="Black"/>
  <Rectangle Width="100" Stroke="Black"
             Height="{Binding ActualWidth, ElementName=source, Mode=Default,
                              Converter={StaticResource MultiplierConverter},
                              ConverterParameter=2}"/>
</StackPanel>

Now the second rectangle will be twice the hight of the first rectangle and can be adjusted with ConverterParameter. Unfortunately you can't bind ConverterParameter to another property, not sure why that limitation exists.

Brett Ryan