另一种方法是让转换器继承 DependencyObject(或 FrameworkElement)。这允许您声明依赖属性,从而可以从 XAML(甚至是 Binding)设置其值。
示例:用于乘以指定因子的值的转换器,该因子是从自定义控件 (MyControl) 中的属性(因子值)获取的。
转换器:
public class MyConverter : DependencyObject, IValueConverter
{
// The property used as a parameter
public double Factor
{
get { return (double) GetValue(FactorProperty); }
set { SetValue(FactorProperty, value); }
}
// The dependency property to allow the property to be used from XAML.
public static readonly DependencyProperty FactorProperty =
DependencyProperty.Register(
"Factor",
typeof(double),
typeof(MyConverter),
new PropertyMetadata(1.15d));
#region IValueConverter Members
object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// Use the property in the Convert method instead of "parameter"
return (double) value * Factor;
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
在 XAML 中使用:
<MyConverter x:Key="MyConv"
Factor={Binding ElementName=MyControl, Path=FactorValue}
/>
因此,您现在可以为转换器中需要的每个参数声明一个依赖属性并绑定它。