[英]how to check if the source path for an bitmapimage is valid in c# mvvm
我試圖獲取圖像運行時並基於ImageFilePathName搜索圖像。 但是有可能圖像不存在但仍然使用空圖像創建源路徑。 如果源中包含有效的文件或圖像,請任何人都可以建議如何檢查。 謝謝
public object Convert(object value, Type targetType, object parameter, string culture)
{
StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
string installFolderPath = installFolder.Path;
const string LOGO_KIND_SMALL = "Small";
ImageSource source;
string logoImageFilePathName;
try
{
int logoId = Int32.Parse((string)value);
logoImageFilePathName = string.Format("{0}\\{1}\\Logos\\Chan\\{2}\\{3:0000}.png", installFolderPath, "Assets", LOGO_KIND_SMALL, logoId);
try
{
source = new BitmapImage(new Uri(logoImageFilePathName));
return source;
}
catch(Exception ex)
{
Logger.LogError(ex.Message);
}
}
catch (Exception ex)
{
Logger.LogError(ex.Message);
}
logoImageFilePathName = string.Format("{0}\\{1}\\Logos\\Channels\\{2}\\{3}.png", installFolderPath, "Assets", LOGO_KIND_SMALL, "0000");
source = new BitmapImage(new Uri(logoImageFilePathName));
return source;
}
public object ConvertBack(object value, Type targetType, object parameter, string culture)
{
throw new NotSupportedException();
}
要檢查並查看路徑是否有效,您可以使用File.Exists(path);
。 但只是為了知識,如果你想看看字符串是否是一個路徑或只是文本Uri.IsWellFormedUriString(parameter, UriKind.Absolute)
所以你會用:
public object Convert(object value, Type targetType, object parameter, string culture)
{
string installFolderPath = System.Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
const string LOGO_KIND_SMALL = "Small";
var logoImageFilePathName = string.Format("{0}\\Assets\\Logos\\Chan\\{1}\\{2:0000}.png"
, installFolderPath
, LOGO_KIND_SMALL
, Int32.Parse((string)value));
// Check for file
return (File.Exists(logoImageFilePathName))
? new BitmapImage(new Uri(logoImageFilePathName))
: null;
}
public object ConvertBack(object value, Type targetType, object parameter, string culture)
{
throw new NotSupportedException();
}
只是注意:當你使用像string.Format()
這樣的方法時,如果你有一個硬編碼的路徑,你應該把它放在字符串中,如上所述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.