![](/img/trans.png)
[英]Binding CollectionViewSource through Converter not triggering Converter when Item is added
[英]CollectionViewSource Items binding with value converter
在我的WPF應用程序中,有一個自定義值轉換器,其中Convert方法接收一個ReadOnlyObservableCollection值參數。
通過以下綁定在XAML中調用此值轉換器:
<TextBlock Grid.Column="2" Text="{Binding Items, Converter={StaticResource totalCutsConverter}}"/>
其中Items來自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;
}
}
老實說,在轉換器中簡單地將其轉換為所需的值類型會容易得多,但是如果需要,可以在這里使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.