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

后端 未结 5 1103
天命终不由人
天命终不由人 2021-01-31 09:34

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 exact

5条回答
  •  生来不讨喜
    2021-01-31 09:42

    @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();
            }
        }
    }
    

提交回复
热议问题