我使用WPF提供的TreeView控件創建文件資源管理器應用程序。我已經對它進行了自定義,使其顯示路徑旁邊的文件圖標。我正在使用IValueConverter將路徑轉換爲所需的圖像,我基於此頁面:http://www.codeproject.com/Articles/21248/A-Simple-WPF-Explorer-Tree綁定轉換器不適用於根TreeViewItem元素(WPF)
它主要起作用!除了根TreeViewItems由於某些原因不顯示圖標。我在IValueConverter :: Convert()函數上放置了一個斷點,並確認它不會爲根節點執行,而是在所有子節點之後執行。
VS輸出窗口顯示沒有綁定錯誤,所以我不知道如何發生這種情況。有任何想法嗎?
轉換代碼:
[ValueConversion(typeof(string), typeof(bool))]
public class HeaderToImageConverter : IValueConverter
{
public static HeaderToImageConverter Instance = new HeaderToImageConverter();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((value as string).Contains(@"\"))
{
Uri uri = new Uri("pack://application:,,,/Images/diskdrive.png");
BitmapImage source = new BitmapImage(uri);
return source;
}
else
{
Uri uri = new Uri("pack://application:,,,/Images/folder.png");
BitmapImage source = new BitmapImage(uri);
return source;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException("Cannot convert back");
}
}
TreeView控件XAML:
<TreeView Grid.Column="0" Name="fileExplorer" Margin="8,8,8,8">
<TreeView.Resources>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Width="20" Height="20" Stretch="Fill" Source="{Binding Converter={x:Static local:HeaderToImageConverter.Instance}}" />
<TextBlock Text="{Binding}" Margin="5,0" VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TreeView.Resources>