Search code examples
silverlightxamlbindingivalueconverterdependencyobject

Binding in Converter?


I'm trying to make a custom converter that inherits from DependencyObject, but it doesn't work:

Converter:

public class BindingConverter : DependencyObject , IValueConverter
{
  public object Value
  {
    get { return (object)GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
  }
  public static readonly DependencyProperty ValueProperty =
      DependencyProperty.Register("Value", typeof(object), typeof(BindingConverter), new PropertyMetadata(null));


  public object Convert(object value, Type targetType, object parameter, Globalization.CultureInfo culture)
  {
    Debug.Assert(Value != null); //fails
    return Value;
  }

  public object ConvertBack(object value, Type targetType, object parameter, Globalization.CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}

Xaml:

<StackPanel x:Name="this">
  <!--works-->
  <ContentControl Content="{Binding ActualHeight, ElementName=this}"/>
  <!--doesn't work-->
  <ContentControl>
    <Binding>
      <Binding.Converter>
        <BindingConverter Value="{Binding ActualHeight, ElementName=this}" />
      </Binding.Converter>
    </Binding>
  </ContentControl>
  <TextBlock Text="{Binding Animals}"/>
</StackPanel>

Am I missing out anything?


Solution

  • I have some places in my projects where I needed similar functionality. Can't show you exact sample, just an idea:

    • perhaps you have to inherit from FrameworkElement, not IValueConverter, Something like this:

      public class BindingHelper : FrameworkElement    
      
    • in the BindingHelper class, set Visibility to Collapsed and IsHitTestVisible to false;

    • to make it working, insert it into visual tree directly. In your example, it should be a child of the StackPanel. So, it will have the same DataContext as other StackPanel children;
    • then, you can add one ore more dependency properties depending on your needs. For example, you might have single property for the source of data and some different properties which you then will use as converter return values. Handle all changes to the source property in your BindingHelper class and change output properties accordingly;
    • bind other controls to properties of the BindingHelper class using ElementName syntax