C# wpf、寄存器DP、可绑定转换器参数

C# wpf、寄存器DP、可绑定转换器参数,c#,wpf,data-binding,valueconverter,C#,Wpf,Data Binding,Valueconverter,XAML: [ValueConversion(typeof(object), typeof(object))] public class BindableConvertor : DependencyObject, IValueConverter { public object BindableParameter { get { return GetValue(MyPropertyProperty); } set { SetValue(MyPrope

XAML:

[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();
    }
}

最后:

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

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

但如果我这样做:

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

。。。然后它就完美地工作了


知道为什么吗?

这可能是因为转换器继承自DependencyObject。请改用Freezable。

这可能是因为转换器继承自DependencyObject。请改为尝试Freezable。

在应用程序的资源中实例化转换器时,可能没有设置DataContext,因此,
AnyTargetProperty
绑定没有源对象。将它放在主窗口的资源中,或者放在您使用它的任何地方。或者,不要将其作为资源,而是在设置ItemsSource绑定时将其实例化。在应用程序的资源中实例化转换器时,可能没有DataContext集,因此,
AnyTargetProperty
绑定没有源对象。将它放在主窗口的资源中,或者放在您使用它的任何地方。或者,不要让它成为一个资源,而是在设置ItemsSource binding.Thx时将其实例化!这就是解决办法。但是你能解释一下“Freezable”是如何工作的吗?或者只是参考一下合适的博客?谢谢!这就是解决办法。但是,你能解释一下“Freezable”是如何工作的,或者仅仅是引用合适的博客吗?。。
        <local:BindableConvertor x:Key="MyConvertor" BindableParameter="Constant text here..." />