绑定转换器作为内部类?

Rob*_*Dam 8 .net c# wpf xaml

我有一个使用绑定转换器的UserControl.我把转换器变成了一个内部类

public partial class MyPanel : UserControl
{
    public class CornerRadiusConverter : IValueConverter
    {
Run Code Online (Sandbox Code Playgroud)

如何从XAML引用Converter类?以下不起作用:

<controls:MyPanel.CornerRadiusConverter x:Key="CornerRadiusConverter" />
Run Code Online (Sandbox Code Playgroud)

它给出了这个错误:

XML命名空间'clr-namespace:MyApp.Windows.Controls'中不存在标签'LensPanel.CornerRadiusConverter'

Tho*_*que 3

我再次思考这个问题,我想出了类似于 Dennis 的解决方案:创建一个带有 Type 属性的“代理”转换器类,它将创建实际转换器的实例并将转换委托给它。

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
}
Run Code Online (Sandbox Code Playgroud)

你这样使用它:

<Window.Resources>
    <my:Converter x:Key="CornerRadiusConverter" Type="{x:Type controls:MyPanel+CornerRadiusConverter}"/>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)