一個使用轉換器來將選中的列表框項目的文本完全改變爲文件名。
在下面的例子中,它旁邊有一個列表和一個文本框。選擇一個項目後,綁定到列表SelectedItem
的文本框會提取傳遞給轉換器的變化字符串,該轉換器僅返回要顯示的文件名。
例
![enter image description here](https://i.stack.imgur.com/IR31t.png)
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>
真棒,正是我一直在尋找的,太感謝你了! –