I need to determine the StringFormat some associated TextBlocks at runtime based on the unit system identified in the object that should be connected.
I have a converter with the Dependency property that I would like to bind to. The Bound value is used to determine the conversion process.
public class UnitConverter : DependencyObject, IValueConverter { public static readonly DependencyProperty IsMetricProperty = DependencyProperty.Register("IsMetric", typeof(bool), typeof(UnitConverter), new PropertyMetadata(true, ValueChanged)); private static void ValueChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { ((UnitConverter)source).IsMetric = (bool)e.NewValue; } public bool IsMetric { get { return (bool)this.GetValue(IsMetricProperty); } set { this.SetValue(IsMetricProperty, value); } } object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (IsMetric) return string.Format("{0:0.0}", value); else return string.Format("{0:0.000}", value); } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }
Declare Converter
<my:UnitConverter x:Key="Units" IsMetric="{Binding Path=IsMetric}"/>
and bind TextBlock
<TextBlock Text="{Binding Path=Breadth, Converter={StaticResource Units}}" Style="{StaticResource Values}"/>
However, I get the following error:
System.Windows.Data error: 2: Cannot find the FrameworkElement or FrameworkContentElement control for the target element. BindingExpression: Path = IsMetric; DataItem = NULL; target element - "UnitConverter" (HashCode = 62641008); target - isMetric (type "Boolean")
I assume this is initialization before I set the datacontext, and therefore I don't need to bind the IsMetric property. How can I achieve the desired result?
c # data-binding wpf ivalueconverter
Cadair idris
source share