Binding to element in WPF: can the Path expression do math?
I'm trying to bind a control to the 开发者_StackOverflow社区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!
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)}"
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;
}
}
No, standart binding doesn't support expressions in Path. But you can look at my project CalcBinding, which was developed specially to resolve this problem and some others. Say, you can write something like:
<Button Content="{c:Binding ElementName=grid, Path=ActualWidth+Height}"/>
or
<Label Content="{c:Binding A+B+C }" />
or
<Button Visibility="{c:Binding IsChecked, FalseToVisibility=Hidden}" />
where A, B, C, IsChecked - properties of viewModel and it will work properly
Goodluck!
@Rachel's MathConverter worked great for me, however I switched out the expression parsing and just left that bit to NCalc. That way I didn't have to worry about operator precedence.
using NCalc;
using System;
using System.Globalization;
using System.Windows.Data;
namespace MyProject.Utilities.Converters
{
public class MathConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// Parse value into equation and remove spaces
string expressionString = parameter as string;
expressionString = expressionString.Replace(" ", "");
expressionString = expressionString.Replace("@VALUE", value.ToString());
return new Expression(expressionString).Evaluate();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
Take a look at my MathConverter
project. It allows for very advanced expressions, including string formatting.
In particular, your expression would be handled as such:
Height="{Binding ActualHeight, ConverterParameter=x/2, Converter={StaticResource math}}"
There are loads of examples, as well as a basic introduction of how to use it on the project's homepage.
精彩评论