WPF绑定:如何将文件路径列表中的名称绑定到ListBox中的TextBlock文本?
我试图将文件路径给定的文件名绑定到TextBlock.文件路径存储在绑定到ListBox的ItemsSourceProperty的列表中. TextBlock设置为DataTemplate.
我的问题是:如何获取没有路径和扩展名的名称并将其绑定到TextBlock?

XAML代码可获得更好的解释:

<ListBox Name="MyListBox" Margin="2">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

以及后面的代码:

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
List<string> PathList = Directory.GetFiles(path, "*.txt").ToList();

Binding myBind = new Binding();
myBind.Source = PathList;

myListBox.SetBinding(ListBox.ItemsSourceProperty, myBind);
最佳答案
人们使用转换器来更改所选列表框项目的文本,该文本已完全路径到文件名.

在以下示例中,旁边有一个列表和一个文本框.选择一个项目后,绑定到列表的SelectedItem的文本框将提取路径字符串,该字符串将传递到转换器,转换器仅返回要显示的文件名.

enter image description here

XAML

<Window x:Class="WPFStack.ListBoxQuestions"
 xmlns:local="clr-namespace:WPFStack"
 xmlns:converters="clr-namespace:WPFStack.Converters"
.../>

<StackPanel Orientation="Horizontal">
    <StackPanel.Resources>
        <converters:PathToFilenameConverter x:Key="FilenameConverter" />

        <x:Array x:Key="FileNames" Type="system:String">
            <system:String>C:\Temp\Alpha.txt</system:String>
            <system:String>C:\Temp\Beta.txt</system:String>
        </x:Array>

    </StackPanel.Resources>

    <ListBox  Name="lbFiles"
              ItemsSource="{StaticResource FileNames}" />

    <TextBlock Text="{Binding SelectedItem, 
                              ElementName=lbFiles,
                              Converter={StaticResource FilenameConverter}}"
                Margin="6,0,0,0" />

</StackPanel>

转换器

namespace WPFStack.Converters
{
public class PathToFilenameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        object result = null;

        if (value != null)
        {
            var path = value.ToString();

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

        return result;

    }

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

ItemTemplate转换器的使用

转换器可以在模板中重复使用

 <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Converter={StaticResource FilenameConverter}}"/>
        </DataTemplate>
  </ListBox.ItemTemplate>
点击查看更多相关文章

转载注明原文:WPF绑定:如何将文件路径列表中的名称绑定到ListBox中的TextBlock文本? - 乐贴网