如何对 XAML 绑定值进行计算:反转、相乘、相减或相加?

问题描述 投票:0回答:2

第一;这个问题是反问,我有答案!我从这里得到了很多帮助,所以我想把这个巧妙的技巧还给我。

假设您有一个想要绑定的值,但它在某种程度上或有些错误。

  • 我遇到过这样的情况:我想要绑定到一个值,但是当该值为 1 时,我需要 0,反之亦然。
  • 曾经有一段时间,我想将元素的宽度绑定到父元素的宽度 - 68px。
wpf xaml binding converters
2个回答
17
投票

输入FirstDegreeFunctionConverter

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace GenericWPF
{
    /// <summary>
    /// Will return a*value + b
    /// </summary>
    public class FirstDegreeFunctionConverter : IValueConverter
    {
        public double A { get; set; }
        public double B { get; set; }

        #region IValueConverter Members

        public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
        {
            double a = GetDoubleValue( parameter, A );

            double x = GetDoubleValue( value, 0.0 );

            return ( a * x ) + B;
        }

        public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
        {
            double a = GetDoubleValue( parameter, A );

            double y = GetDoubleValue( value, 0.0 );

            return ( y - B ) / a;
        }

        #endregion


        private double GetDoubleValue( object parameter, double defaultValue )
        {
            double a;
            if( parameter != null )
                try
                {
                    a = System.Convert.ToDouble( parameter );
                }
                catch
                {
                    a = defaultValue;
                }
            else
                a = defaultValue;
            return a;
        }
    }
}

如何使用?

您在资源部分为每次用途创建一个资源:

<GenericWPF:FirstDegreeFunctionConverter x:Key="ReverseOne"
                            A="-1"
                            B="1" />

<Border Opacity="{Binding Path=Opacity
    , ElementName=daOtherField
    , Converter={StaticResource ReverseOne}}" />

<GenericWPF:FirstDegreeFunctionConverter x:Key="ListboxItemWidthToErrorWidth"
     A="1"
     B="-68" />

<TextBox MaxWidth="{Binding Path=ActualWidth
   , Converter={StaticResource ListboxItemWidthToErrorWidth}
   , RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}" />

这个名字来源于函数 y = ax + b (挪威语称为“一次函数”),当然也可以将其升级为二次函数 y= ax^2 + bx + c,但我还没有找到它的用途。

我遇到过一种情况,我想根据宽度制作列。每次宽度增加 200 像素时,我希望容器向我显示另一列。当时我硬编码了一个转换器,但我应该制作一个 y=(a/x) + b 转换器。

现在,我应该给这个转换器命名什么,以便每个人都明白它是什么?由于我是挪威人,所以我用了我们在学校学到的表达方式,直接翻译。如果您有建议或意见,请告诉我。 您想到的任何改进或改进也将不胜感激......


也许“LinearTransformConverter”可以更好地传达转换器为您做什么,我会考虑一下。 还有其他建议吗? 托尔


7
投票

更好的是

PolynomialConverter
,这是单向版本:

public class PolynomialConverter : IValueConverter
{
    public DoubleCollection Coefficients { get; set; }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        double x = (double)value;
        double output = 0;
        for (int i = Coefficients.Count - 1; i >= 0 ; i--)
            output += Coefficients[i] * Math.Pow(x, (Coefficients.Count - 1) - i);

        return output;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //This one is a bit tricky, if anyone feels like implementing this...
        throw new NotSupportedException();
    }
}

示例:

<!-- x^2 -->
<vc:PolynomialConverter Coefficients="1,0,0"/>
<!-- x + 5 -->
<vc:PolynomialConverter Coefficients="1,5"/>
<!-- 2x + 4 -->
<vc:PolynomialConverter Coefficients="2,4"/>

或者可以使用 ConverterParameter 来不在转换器本身中设置系数。

DoubleCollection coefficients = DoubleCollection.Parse((string)parameter);
//...
© www.soinside.com 2019 - 2024. All rights reserved.