首先,这个问题是修辞性的,我有答案!我从这里找到了很多帮助,所以我想回馈一个不错的技巧。
假设你有一个想要绑定的值,但它可能在某些方面或某种程度上有误。
- 我曾遇到这样一种情况,我想要将一个值绑定到另一个值,但当这个值为1时,我需要0,反之亦然。
- 有一次我想将一个元素的宽度绑定到父元素的宽度减去68像素。
首先,这个问题是修辞性的,我有答案!我从这里找到了很多帮助,所以我想回馈一个不错的技巧。
假设你有一个想要绑定的值,但它可能在某些方面或某种程度上有误。
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}}}" />
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"/>
DoubleCollection coefficients = DoubleCollection.Parse((string)parameter);
//...