绑定到WPF中的元素:Path表达式可以进行数学运算吗?
我正在尝试使用ElementName
和Path将控件绑定到父级的Height / width属性。 但是,我不想绑定到实际高度,而是高度的一半。 Path
表达式可以进行数学运算吗?
例如Path={ActualHeight/2}
我找不到办法做到这一点。 还有其他聪明的方法吗?
谢谢!
不,你不应该使用绑定转换器
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; } }
我使用MathConverter
在我的XAML绑定中进行数学运算。转换器代码可以在这里找到,它的使用方式如下:
Height="{Binding ElementName=RootWindow, Path=ActualHeight, Converter={StaticResource MathConverter}, ConverterParameter=@VALUE/2}"
它还将处理更高级的数学方程式
Height="{Binding ElementName=RootWindow, Path=ActualHeight, Converter={StaticResource MathConverter}, ConverterParameter=((@VALUE-200)*.3)}"
不,标准绑定不支持Path中的表达式。 但是你可以看看我的项目CalcBinding ,它是专门为解决这个问题而开发的。 说,你可以这样写:
要么
要么
其中A,B,C,IsChecked – viewModel的属性,它将正常工作
祝好运!
@Rachel的MathConverter对我来说非常有用,但是我将表达式解析出来并将该位留给了NCalc。 这样我就不用担心运算符优先级了。
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(); } } }
看看我的MathConverter
项目。 它允许非常高级的表达式,包括字符串格式。
特别是,您的表达式将按如下方式处理:
Height="{Binding ActualHeight, ConverterParameter=x/2, Converter={StaticResource math}}"
有大量示例,以及如何在项目主页上使用它的基本介绍。