How to create a binding that includes some kind of formula?

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

An example might be the following: mirroredObject- this is the object that I want to use half its width for the width of the object Border.

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

I have other situations in which a property that I could bind could be the sum of the width of the other elements, how could I achieve this?

Decision

Please refer to my answer for the solution that lenanovd's answer helped.

+3
source share
2 answers

, int int, . , , , .

, .

+6

levanovd , . - , levanovd.

[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;
    }
}

XAML

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

, .

<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>

ConverterParameter. , ConverterParameter , , .

+2

Source: https://habr.com/ru/post/1724463/


All Articles