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

时间:2016-03-21 19:06:13

标签: c# wpf xaml listbox converter

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

数据来自使用Dialog填充的ObservableCollection

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

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

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

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

我绑定到我的listbox 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]

我哪里错了?

谢谢

1 个答案:

答案 0 :(得分:3)

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>
相关问题