[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}}" />
结果:
系统.Windows。数据错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement。BindingExpression:路径=;数据项=空;目标元素是“BindableConvertor”(HashCode=19986012);目标属性为“BindableParameter”(类型为“Object”)。
我的“BindableParameter”总是等于默认值(null)。
但如果我这样做:
<local:BindableConvertor x:Key="MyConvertor" BindableParameter="Constant text here..." />
…然后它就完美地工作了。
你知道为什么吗?