我知道这是一个古老的问题,但也许这会对遇到它的人有用。我找到了解决办法是如下:
public class WattHoursConverter : FrameworkElement, IValueConverter
{
#region Unit (DependencyProperty)
/// <summary>
/// A description of the property.
/// </summary>
public string Unit
{
get { return (string)GetValue(UnitProperty); }
set { SetValue(UnitProperty, value); }
}
public static readonly DependencyProperty UnitProperty =
DependencyProperty.Register("Unit", typeof(string), typeof(WattHoursConverter),
new PropertyMetadata("", new PropertyChangedCallback(OnUnitChanged)));
private static void OnUnitChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((WattHoursConverter)d).OnUnitChanged(e);
}
protected virtual void OnUnitChanged(DependencyPropertyChangedEventArgs e)
{
}
#endregion
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// you can use the dependency property here
...
}
}
,并在您的XAML:
<UserControl.Resources>
<converters:WattHoursConverter x:Key="WattHoursConverter" Unit="{Binding UnitPropFromDataContext}"/>
</UserControl.Resources>
....
<TextBlock Grid.Column="1" TextWrapping="Wrap" Text="{Binding TotalCO2, Converter={StaticResource KgToTonnesConverter}}" FontSize="13.333" />
+1的另一种方法。 – iMatoria 2011-09-05 10:52:18
转换器是否从`DependencyObject`继承?我正在创作一个自定义控件,我需要根据控件中的另一个属性来格式化绑定的对象。 – Shimmy 2012-02-22 21:43:10
“将整个绑定对象传递给转换器”是什么意思? – 2012-11-18 00:16:06