Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding converter as inner class?

Tags:

c#

.net

wpf

xaml

I have a UserControl that uses a binding converter. I've made the converter an inner class of

public partial class MyPanel : UserControl
{
    public class CornerRadiusConverter : IValueConverter
    {

How do I reference the Converter class from the XAML? The following does not work:

<controls:MyPanel.CornerRadiusConverter x:Key="CornerRadiusConverter" />

It gives this error:

The tag 'LensPanel.CornerRadiusConverter' does not exist in XML namespace 'clr-namespace:MyApp.Windows.Controls'

like image 785
Robbert Dam Avatar asked May 14 '09 12:05

Robbert Dam


1 Answers

I was thinking about this problem again, and I came up with something similar to Dennis's solution : create a "proxy" converter class, with a Type property, which will create the instance of the actual converter and delegate the conversion to it.

public class Converter : IValueConverter
{
    private Type _type = null;
    public Type Type
    {
        get { return _type; }
        set
        {
            if (value != _type)
            {
                if (value.GetInterface("IValueConverter") != null)
                {
                    _type = value;
                    _converter = null;
                }
                else
                {
                    throw new ArgumentException(
                        string.Format("Type {0} doesn't implement IValueConverter", value.FullName),
                        "value");
                }
            }
        }
    }

    private IValueConverter _converter = null;
    private void CreateConverter()
    {
        if (_converter == null)
        {
            if (_type != null)
            {
                _converter = Activator.CreateInstance(_type) as IValueConverter;
            }
            else
            {
                throw new InvalidOperationException("Converter type is not defined");
            }
        }
    }

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        CreateConverter();
        return _converter.Convert(value, targetType, parameter, culture);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        CreateConverter();
        return _converter.ConvertBack(value, targetType, parameter, culture);
    }

    #endregion
}

You use it like that :

<Window.Resources>
    <my:Converter x:Key="CornerRadiusConverter" Type="{x:Type controls:MyPanel+CornerRadiusConverter}"/>
</Window.Resources>
like image 132
Thomas Levesque Avatar answered Oct 07 '22 22:10

Thomas Levesque