c# WPF值转换器接收整个集合而不是单个项目作为值参数

本文关键字:单个 项目 参数 值参 集合 转换器 WPF | 更新日期: 2023-09-27 18:17:53

我有一个c# WPF 4.51应用程序。在我的一个XAML表单上,我有一个列表框,它的ItemsSource属性绑定到我的主ViewModel类型为Collection的属性。当集合的类型为string时,一切正常,我在列表框中看到了字符串集合。

但随后我将集合中的类型更改为一个名为ObservableStringExt的类。该类有两个字段:StrItem包含我想要在列表框中显示的字符串,以及IsSelected,一个支持字段。然后创建了一个值转换器来提取StrItem字段并返回它。

然而,当我查看传递给值转换器的Convert()方法的targetType时,我看到了一个类型IEnumerable。假设该参数中的Count属性与期望的列表项数量匹配,那么看起来Convert()方法接收对整个集合的引用,而不是ObservableStringExt(集合中每个项的类型)的引用。这当然是个问题。是什么导致了这种情况?我在Windows Phone和WinRT (Windows商店应用程序)上做过很多次这样的事情,没有遇到任何问题。

以下是值转换器的代码:
public class ObservableStringExtToStrItem : IValueConverter
{
    // The targetType of the value received is of type IEnumerable, not ObservableStringExt.
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is ObservableStringExt)
            return (value as ObservableStringExt).StrItem;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

下面是列表框的XAML代码。注意 command_frequentyused 是在主视图模型中发现的类型为ObservableCollectionWithFile的属性,它是整个表单的数据上下文

<ListBox x:Name="listFrequentlyUsedCommands"
             Width="278"
             Height="236"
             Margin="30,103,0,0"
             HorizontalAlignment="Left"
             VerticalAlignment="Top"
             ItemsSource="{Binding Commands_FrequentyUsed.Collection,
                                   Converter={StaticResource ObservableStringExtToStrItem}}" />

下面是包含列表框绑定的Collection的类和Collection包含的类的代码:

public class ObservableStringExt
{
    public string StrItem { get; set;}
    public bool IsSelected{ get; set; }
}
public class ObservableCollectionWithFile : BaseNotifyPropertyChanged
{
    public const string CollectionPropertyName = "Collection";
    private ObservableCollection<ObservableStringExt> _observableCollection = new ObservableCollection<ObservableStringExt>();
    public ObservableCollection<ObservableStringExt> Collection
    {
        get { return _observableCollection; }
        private set { SetField(ref _observableCollection, value); }
    }
} // public class ObservableCollectionWithFile

c# WPF值转换器接收整个集合而不是单个项目作为值参数

我刚刚遇到了同样的问题。不确定它应该如何正常工作,但更改转换器也转换项目列表有帮助(我发现这比为列表创建单独的转换器更容易)

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    var list = value as IEnumerable<ObservableStringExt>;
    if (list != null)
    {
        return list.Select(x => Convert(x, typeof(string), null, culture));
    }
    if (value is ObservableStringExt)
        return (value as ObservableStringExt).StrItem;
}