【发布时间】:2016-10-06 11:04:37
【问题描述】:
我的设计师在 MVVM 项目中遇到问题。
我有一个 TreeView 和一个自定义 DataTemplate :
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Name="img" Width="20" Height="20" Stretch="Fill"
Source="{Binding
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type TreeViewItem}},
Path=Header,
Converter={StaticResource HeaderToImageConverter}}"
/>
<TextBlock Text="{Binding}" Margin="5,0" />
</StackPanel>
</DataTemplate>
资源声明:
<Window x:Class="BlobWorld.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Core="clr-namespace:BlobWorld;assembly="
xmlns:helper="clr-namespace:BlobWorld.Helper"
mc:Ignorable="d"
Title="MainWindow" Height="350.459" Width="746.561"
DataContext="{DynamicResource MainWindowViewModel}">
<Window.Resources>
<helper:HeaderToImageConverter x:Key="HeaderToImageConverter"/>
</Window.Resources>
我的转换器是:
public class HeaderToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((value as string).Contains(@"."))
{
Uri uri = new Uri("pack://application:,,,/images/File.png");
BitmapImage source = new BitmapImage(uri);
return source;
}
else
{
if (!(value as string).Contains(@":"))
{
Uri uri = new Uri("pack://application:,,,/images/folder.png");
BitmapImage source = new BitmapImage(uri);
return source;
}
else
{
Uri uri = new Uri("pack://application:,,,/images/diskdrive.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");
}
}
它在运行时完美运行,但是当我在 Visual Studio 中使用 xaml“设计”窗口而不是查看 Windows 的外观时,我只有一个 IOException : Cannot locate resource 'images/folder.png'
我的问题来自哪里? 我该如何解决?
【问题讨论】:
-
可能最简单的解决方法是在转换器中使用detect design mode,在这种情况下不要尝试解析图像(返回
null)。 -
@Sinatr 如果工作正常,我现在可以看到我的 Windows,但是(当我返回 null ...)我没有看到我的图像,所以知道我的渲染仍然很烦人。如果您有办法在特定于设计模式的代码中返回我的图像,我会接受它作为答案。
-
@Rom 已经完成了。
-
好的,我也有同样的问题。我用图像创建了一个用户控件,然后当我将用户控件嵌入到窗口中时,图像资源不可用。但是当我编译并运行时,它显示得非常好。我认为这可能是一个非常烦人的 VS 错误。
标签: c# wpf mvvm designer ioexception