【问题标题】:File path to file name String converter not working文件名字符串转换器的文件路径不起作用
【发布时间】:2016-07-08 11:08:28
【问题描述】:

使用 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 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]

我哪里错了?

谢谢

【问题讨论】:

    标签: c# wpf xaml listbox converter


    【解决方案1】:

    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>
    

    【讨论】:

    • 就是这样。谢谢
    猜你喜欢
    • 2012-12-15
    • 1970-01-01
    • 2020-04-14
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多