文件名字符串转换器的文件路径不起作用

File path to file name String converter not working

使用 wpf ListBox 我试图显示文件名列表而不显示完整路径(对用户来说更方便)。

数据来自使用对话框填充的 ObservableCollection

    private ObservableCollection<string> _VidFileDisplay = new ObservableCollection<string>(new[] {""});

    public ObservableCollection<string> VidFileDisplay
    {
        get { return _VidFileDisplay; }
        set { _VidFileDisplay = value; }
    }

最后我想 select 一些项目并取回完整的文件路径。为此,我有一个转换器:

  public class PathToFilenameConverter : IValueConverter
  {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
          //return Path.GetFileName(value.ToString());
          string result = null;
          if (value != null)
          {
              var path = value.ToString();

              if (string.IsNullOrWhiteSpace(path) == false)
                  result = Path.GetFileName(path);
          }
          return result;
      }

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

我绑定到我的列表框 itemsource :

<ListBox x:Name="VideoFileList" Margin="0" Grid.Row="1" Grid.RowSpan="5" Template="{DynamicResource BaseListBoxControlStyle}" ItemContainerStyle="{DynamicResource BaseListBoxItemStyle}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemsSource="{Binding Path=DataContext.VidFileDisplay, Converter={StaticResource PathToFileName},ElementName=Ch_Parameters, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Path=SelectedVidNames,ElementName=Ch_Parameters, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">

没有转换器,它工作正常(但当然这是列表框中显示的完整路径)。使用转换器,我每行一个字符......显示这个:

System.Collections.ObjectModel.ObservableCollection`1[System.String]

我哪里错了?

谢谢

ItemsSource 中,绑定转换器适用于整个列表,而不适用于集合中的每个项目。如果你想为每个项目应用你的转换器,你需要这样做 ItemTemplate

<ListBox x:Name="VideoFileList" ItemsSource="{Binding Path=DataContext.VidFileDisplay, ElementName=Ch_Parameters}" ...>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=., Converter={StaticResource PathToFileName}}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>