File path to file name String converter not workin

2019-03-04 17:30发布

问题:

Using a wpf ListBox I'm trying to display a list of filename without displaying the full path (more convenient for user).

Data comes from an ObservableCollection which is filled using Dialog.

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

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

In the end I want to select some items and get back the full file path. For this I have a converter :

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

Which I bind to my 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}">

Without the converter, it is working fine (but of course this is the full path displayed in the listbox). With the converter I have one character per line... displaying this :

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

Where am I wrong ?

Thank you

回答1:

In ItemsSource binding converter applies to the whole list and not to each item in the collection. If you want to apply your converter per item you need to do it 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>