我正在尝试将文件路径给定的文件名绑定(bind)到 TextBlock。文件路径存储在一个列表中,该列表绑定(bind)到 ListBox 的 ItemsSourceProperty。 TextBlock 设置为 DataTemplate。 我的问题是:如何获取没有路径和扩展名的名称并将其绑定(bind)到 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);
最佳答案
一个使用转换器来更改选定的列表框项目的文本,该项目的完整路径仅指向文件名。
在下面的示例中,有一个列表和旁边的一个文本框。选择一个项目后,绑定(bind)到列表的 SelectedItem
的文本框会提取路径字符串,该字符串将传递给转换器,该转换器仅返回要显示的文件名。
示例
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>
关于c# - WPF 绑定(bind) : How to bind a name from a list of filepaths to text of TextBlock in ListBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32122461/