IValueConverter
相対ファイル パスを に変換する WPF がありますBitmapImage
。
コード:
public class RelativeImagePathToImage : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var relativePath = (string)value;
if (string.IsNullOrEmpty(relativePath)) return Binding.DoNothing;
var path = "pack://application:,,,/" + value;
var uri = new Uri(path);
return new BitmapImage(uri);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
問題:
このコンバーターは、プロジェクトにリンクとして追加されたファイルで使用しようとするまでは正常に機能していました (ソリューション エクスプローラー -> 既存のアイテムの追加 -> リンクとして追加)。画像ファイルBuildAction
は に設定されContent
、ファイルは とマークされていますCopy Always
。ファイルは間違いなく「bin」フォルダーに適切にコピーされていますが、何らかの理由で、return new BitmapImage(uri)
.
例外:
System.IO.IOException was unhandled
Message="Cannot locate resource 'images/splash.png'."
Source="PresentationFramework"
質問:
誰かがこれを説明できますか?これは .NET Framework のバグですか、それとも予想される動作ですか? 回避策はありますか、または「リンクとして追加」は画像コンテンツ ファイルのオプションではありませんか?
編集:
わかりました、回避策を見つけました。これが私の改訂されたコンバータークラスです:
public class RelativeImagePathToImage : IValueConverter
{
private static string _rootPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var relativePath = (string)value;
if (string.IsNullOrEmpty(relativePath)) return Binding.DoNothing;
var path = _rootPath + "/" + relativePath;
var uri = new Uri(path);
return new BitmapImage(uri);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
packuri
どうやら、リンクされたファイルで を使用すると、何らかの問題が発生するようです。しかし、なぜ?