IValueConverter and binding a DependencyObject



我有一个ComboBox,我需要在SelectedItem上做一个转换器。问题是IValueConverter需要绑定值,但也需要集合。 配置了一个DependencyObject但它给了我一条错误消息

类型为"System.Windows.Data.Binding"的对象不能转换为类型"System.Collections.ObjectModel.ObservableCollection'1[MyClass]"。

这是我的IValueConverter

public class MyConverter : DependencyObject, IValueConverter
{
public static readonly DependencyProperty FoldersProperty = 
DependencyProperty.Register(nameof(MyCollection), typeof(ObservableCollection<MyClass>), typeof(MyClassModelToMyClassID), new FrameworkPropertyMetadata(new ObservableCollection<MyClass>()));
public ObservableCollection<MyClass> MyCollection
{
get { return GetValue(FoldersProperty) as ObservableCollection<MyClass>; }
set { SetValue(FoldersProperty, value); }
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//Amazing Convert code that uses MyCollection and Value
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
//Amazing ConvertBack code that uses MyCollection and Value
}
}

这是我如何称呼它:

<Page.Resources>
<converter:MyConverter x:Key="Converter" MyCollection="{Binding DataCollection}" />
</Page.Resources>
....
<ComboBox 
ItemsSource="{Binding DataCollection}"
SelectedItem="{Binding Path=MyValue, Converter={StaticResource TaxCodeConverter}}" />

编辑:添加了完整的 IValueConvert 减去转换和转换回来代码

就像 BindingProxy 一样,它需要是一个可冻结的。此外,不要将新的可观察集合传递给元数据。这是一个引用类型,因此此转换器的所有实例都将使用相同的实际集合实例进行初始化。

如果您遇到其他问题,请告诉我,但我已经这样做并能够绑定到依赖项属性。

许多人会争辩说,更好的方法是多重绑定和多值转换器。我认为拥有一个具有描述性名称的强类型属性是有价值的。

public class MyConverter : Freezable, IValueConverter
{
/* omitted: Convert() and ConvertBack() */
public MyConverter()
{
//  Initialize here if you need to
MyCollection = new ObservableCollection<MyClass>();
}
protected override Freezable CreateInstanceCore()
{
return new MyConverter();
}
public static readonly DependencyProperty MyCollectionProperty =
DependencyProperty.Register(nameof(MyCollection), 
typeof(ObservableCollection<MyClass>), typeof(MyConverter),
new FrameworkPropertyMetadata(null));
public ObservableCollection<MyClass> MyCollection
{
get { return GetValue(MyCollectionProperty) as ObservableCollection<MyClass>; }
set { SetValue(MyCollectionProperty, value); }
}
}

XAML 用法将与您在问题中一样:绑定依赖项属性,绑定将更新该MyConverter实例的该属性,前提是页面的 DataContext 具有名为DataCollection的适当类型属性。

<Page.Resources>
<converter:MyConverter x:Key="Converter" MyCollection="{Binding DataCollection}" />
</Page.Resources>

相关内容

  • 没有找到相关文章

最新更新