wpf,注册DP,可绑定转换器参数

时间:2016-01-15 20:12:37

标签: c# wpf data-binding valueconverter

[ValueConversion(typeof(object), typeof(object))]
public class BindableConvertor : DependencyObject, IValueConverter
{
    public object BindableParameter
    {
        get { return GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }

    public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register(
            nameof(BindableParameter),
            typeof(object),
            typeof(BindableConvertor),
            new PropertyMetadata(String.Empty)
            );


    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // actions here...
    }

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

XAML:

<Application.Resources>
    <local:BindableConvertor x:Key="MyConvertor" BindableParameter="{Binding AnyTargetProperty}" />
</Application.Resources>

最后:

<ListBox Name="ViewBox"
                     Grid.Row="0"
                     DisplayMemberPath="Value"
                     ItemsSource="{Binding SomePropertyFromWindowDataContext,
                                           Converter={StaticResource MyConvertor}}" />

结果: System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement。 BindingExpression:路径=;的DataItem = NULL; target元素是'BindableConvertor'(HashCode = 19986012); target属性是'BindableParameter'(类型'Object')。 而我的“BindableParameter”总是等于默认值(null)。

但如果我做了类似的事情:

        <local:BindableConvertor x:Key="MyConvertor" BindableParameter="Constant text here..." />

......然后它完美无缺。

任何想法为什么?

1 个答案:

答案 0 :(得分:0)

可能是因为您的转换器继承自DependencyObject。请尝试使用Freezable。