Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to element in WPF: can the Path expression do math?

I'm trying to bind a control to the parent's Height/width property using ElementName and a Path. However, I don't want to bind to the actual height, but to exactly half the height. Can the Path expression do the math?

e.g. Path={ActualHeight/2}

I couldn't find a way to do that. IS there any other clever approach?

Thanks!

like image 598
John Avatar asked May 03 '10 09:05

John


People also ask

What is path in binding WPF?

Binding path syntax. Use the Path property to specify the source value you want to bind to: In the simplest case, the Path property value is the name of the property of the source object to use for the binding, such as Path=PropertyName . Subproperties of a property can be specified by a similar syntax as in C#.

How does binding work in WPF?

Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.

What are the different data binding modes available in WPF?

<TextBox x:Name="DestinationTextBox" Text="{Binding ElementName=SourceTextBox, Path=Text, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}" Margin="{StaticResource MarginTop}" Width="150"

What is two way binding WPF?

Two way binding is used when we want to update some controls property when some other related controls property change and when source property change the actual control also updates its property.


2 Answers

I use a MathConverter to do math in my XAML bindings.The converter code can be found here and it is used like this:

Height="{Binding ElementName=RootWindow, Path=ActualHeight,                  Converter={StaticResource MathConverter},                  ConverterParameter=@VALUE/2}" 

It will also handle more advanced math equations like

Height="{Binding ElementName=RootWindow, Path=ActualHeight,                 Converter={StaticResource MathConverter},                 ConverterParameter=((@VALUE-200)*.3)}" 
like image 82
Rachel Avatar answered Sep 18 '22 06:09

Rachel


No it can't you should use binding converters

public class MyConverter : IValueConverter { public object Convert(object value, Type  targetType,       object parameter, CultureInfo culture)   {       return (int)value/2;   }    public object ConvertBack(object value, Type targetType,       object parameter, CultureInfo culture)   {     return null;   } } 
like image 29
Arsen Mkrtchyan Avatar answered Sep 19 '22 06:09

Arsen Mkrtchyan