0

I have a bindinglist with INotifyPropertyChanged interface. Things work fine. This bindinglist is a list of file names that is bound to a listbox. I want only the name displayed, not the whole path, but when I select a file name and load the file, I need the whole path.

I am using IValueConverter for this purpose where is use Path.GetFileName property to change full path to file name. Bindings are correct, but my bindinglist is not changing values as I want them to. I am pasting IValueConverter code below. Please let me know what is wrong with this code. i referred conversion 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;
    }

}

EDIT: Values are converted now. But now how to retrieve back the whole path? Shall I keep 2 lists? One for full path and one with name like here. Any better solution?

4

1 回答 1

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;
    }
}

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

希望有帮助!

于 2013-07-01T14:45:13.337 回答