【问题标题】:IValueConverter and convert all values of bindinglistIValueConverter 并转换 bindinglist 的所有值
【发布时间】:2013-07-01 23:09:23
【问题描述】:

我有一个带有 INotifyPropertyChanged 接口的绑定列表。一切正常。 此绑定列表是绑定到列表框的文件名列表。我只想要显示的名称,而不是整个路径,但是当我选择一个文件名并加载文件时,我需要整个路径。

我为此目的使用 IValueConverter,其中使用 Path.GetFileName 属性来更改文件名的完整路径。绑定是正确的,但我的绑定列表并没有按照我的意愿更改值。我在下面粘贴 IValueConverter 代码。请让我知道这段代码有什么问题。我提到了转换here

[ValueConversion(typeof(string), typeof(string))]
public class pathtoname : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter ,CultureInfo culture)
    {
        BindingList<string> ls = value as BindingList<string>;
        ls.Select(x => "WW");
        return ls;//all values should be WW. But they are not.(debugger)
    }

    public object ConvertBack(object value, Type targetType, object parameter,CultureInfo culture)
    {
        return null;
    }

}

编辑:值现在被转换。但是现在如何找回整个路径呢?我要保留 2 个清单吗?一种用于完整路径,另一种名称类似于here。有更好的解决方案吗?

【问题讨论】:

    标签: c# wpf list mvvm ivalueconverter


    【解决方案1】:

    要返回文件名和完整路径,您必须创建一个新类:

    public class MyFile
    {
        public string Filename { get; set; }
        public string Fullpath { get; set; }
    }
    

    之后,您必须在转换器中返回 MyFile 列表

    [ValueConversion(typeof(string), typeof(string))]
    public class pathtoname : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter ,CultureInfo culture)
        {
            BindingList<string> ls = value as BindingList<string>;
            List<MyFile> files = new List<MyFile>();
            foreach (string s in ls)
            {
                files.Add(new MyFile() { Filename = Path.GetFileName(s), Fullpath = s });
            }
    
            return files;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter,CultureInfo culture)
        {
            return null;
        }
    }
    

    最后,在您的 Listbox 中,您可以使用 MyFile 的 DataBinding 属性进行检索

    希望对你有帮助!

    【讨论】:

    • 好的。那行得通。但我现在有另一个问题。我的加载文件丢失了完整路径。关于如何保留完整路径但只显示文件名的提示?
    • 要获取文件名,您可以尝试从 Path 静态类中查看 GetFileName 方法:msdn.microsoft.com/en-us/library/…
    • 啊,我知道。从文件名,我想去一个完整的路径,所以我可以通过另一个函数传递文件。但转换器丢失了信息。
    • 此转换器与 ComboBox 一起使用?
    • 列表框。值显示在列表框中。我点击文件名,应该从硬盘加载文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 2011-07-05
    相关资源
    最近更新 更多