Devo determinare il StringFormat
di alcuni limiti TextBlocks
in fase di esecuzione in base al sistema di unità identificato nell'oggetto da rilegare.IValueConverter con proprietà dipendenza dipendente
Ho un convertitore con una proprietà dipendenze che vorrei associare a. Il valore Bound viene utilizzato per determinare il processo di conversione.
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();
}
}
dichiaro il convertitore
<my:UnitConverter x:Key="Units" IsMetric="{Binding Path=IsMetric}"/>
e legare il TextBlock
<TextBlock Text="{Binding Path=Breadth, Converter={StaticResource Units}}" Style="{StaticResource Values}"/>
Non di meno, ottengo il seguente errore:
System.Windows.Data errore: 2: Impossibile trovare il framework FrameworkElement o FrameworkContentElement per l'elemento di destinazione. BindingExpression: Path = IsMetric; DataItem = null; l'elemento target è 'UnitConverter' (HashCode = 62641008); La proprietà target è 'IsMetric' (tipo 'Boolean')
Immagino che questo sia inizializzato prima di impostare il datacontext e quindi non c'è nulla per associare la proprietà IsMetric
a. Come posso ottenere il risultato desiderato?
Io volevo evitare questo perché ho centinaia di TextBlock e non volevo dover passare e modificarli tutti. –
Grazie amico, mi sono reso conto che stavo proprio impostando la stessa proprietà, beh, se mai fosse stato chiamato così! Il MultiBinding funziona comunque –