C# CollectionViewSource项与值转换器绑定
在我的WPF应用程序中,有一个自定义值转换器,其中Convert方法接收ReadOnlyObservableCollection值参数 此值转换器在XAML中从以下绑定调用:C# CollectionViewSource项与值转换器绑定,c#,wpf,C#,Wpf,在我的WPF应用程序中,有一个自定义值转换器,其中Convert方法接收ReadOnlyObservableCollection值参数 此值转换器在XAML中从以下绑定调用: <TextBlock Grid.Column="2" Text="{Binding Items, Converter={StaticResource totalCutsConverter}}"/> 其中项目来自CollectionViewSource,分组描述如下: <CollectionViewSou
<TextBlock Grid.Column="2" Text="{Binding Items, Converter={StaticResource totalCutsConverter}}"/>
其中项目来自CollectionViewSource,分组描述如下:
<CollectionViewSource x:Key="sheetsViewSource" Source="{Binding}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="MaterialDescription" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
问题是:如何使我的值转换器接收我的特定项类型模型类的集合,而不是通用对象类
换句话说,我想在Convert方法中进行以下转换
ReadOnlyObservableCollection<myClass> col = value as ReadOnlyObservableCollection<myClass>();
有什么想法吗?注释中已经提到了解决方案,即简单地转换转换器中的值。真的没有必要为这个实现任何花哨的东西 话虽如此,我向自己提出了挑战,如果你真的准备好了,那么下面是一个如何做到这一点的例子:
public interface IValueConverter<T> : IValueConverter
{
object Convert(T value, Type targetType, object parameter, CultureInfo culture);
object ConvertBack(T value, Type targetType, object parameter, CultureInfo culture);
}
public abstract class GenericConverter<T> : IValueConverter<T>
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
CheckType(value);
return Convert((T)value, targetType, parameter, culture);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
CheckType(value);
return ConvertBack((T)value, targetType, parameter, culture);
}
private void CheckType(object value)
{
if (value == null)
{
//TODO: Do something about nulls.
}
Type type = typeof(T);
if (value.GetType() != type)
throw new InvalidCastException(string.Format("Converter value could not be cast to: ", type.Name));
}
public abstract object Convert(T value, Type targetType, object parameter, CultureInfo culture);
public abstract object ConvertBack(T value, Type targetType, object parameter, CultureInfo culture);
}
本质上,它只是一个普通的转换器,但在顶部有额外的类型检查和铸造。下面是一个如何使用它的示例:
public class ExampleConverter : GenericConverter<string>
{
public override object Convert(string value, Type targetType, object parameter, CultureInfo culture)
{
//TODO: Convert implementation
return value;
}
public override object ConvertBack(string value, Type targetType, object parameter, CultureInfo culture)
{
//TODO: ConvertBack implementation
return value;
}
}
老实说,在转换器中简单地强制转换为所需的值类型会容易得多,但是如果需要,可以在这里使用。没有IValueConverter的通用变体,因此,您只需检查传入对象是否具有预期类型,并将其强制转换到Convert方法中。您已经可以在Convert方法中执行该强制转换了,是什么阻止了您?另一个不同的问题是,您的值对象实际上不是ReadOnlyObservableCollection。。。但这与转换器无关,毕竟是您对该属性进行了绑定。大家好。我的问题不是如何实现值转换器,也不是铸造对象。真正地我的问题是如何使绑定机制传递特定对象类型的集合,而不是泛型集合。就这样。如果这不可能,我可以接受。但是如果有别的办法,我想知道。