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

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

本文介绍了文件名的文件路径字符串转换器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我绑定到列表框itemsource的位置:

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]

我在哪里错了?

谢谢

推荐答案

ItemsSource中,绑定转换器适用于整个列表,而不适用于集合中的每个项目.如果要对每个项目应用转换器,则需要ItemTemplate

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>

这篇关于文件名的文件路径字符串转换器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 13:11