我想在運行時從一個URI加載BitmapImage。我在我希望通過數據綁定替換的XAML用戶控件中使用默認圖像。這工作。驗證在運行時從URI加載的WPF位圖圖像
我遇到的問題是無效文件用於替換圖像(也許它是一個錯誤的URI,或者URI可能指定一個非圖像文件)。發生這種情況時,我希望能夠檢查BitmapImage對象以查看它是否正確加載。如果沒有,我想堅持使用默認圖像。
這裏的XAML:
<UserControl x:Class="MyUserControl">
<Grid>
<Image
x:Name="myIcon"
Source="Images/default.png" />
</Grid>
</UserControl>
和相關的代碼隱藏:
public static readonly DependencyProperty IconPathProperty =
DependencyProperty.Register(
"IconPath",
typeof(string),
typeof(MyUserControl),
new PropertyMetadata(null, new PropertyChangedCallback(OnIconPathChanged)));
public string IconPath
{
get { return (string)GetValue(IconPathProperty); }
set { SetValue(IconPathProperty, value); }
}
private static void OnIconPathChanged(
object sender,
DependencyPropertyChangedEventArgs e)
{
if (sender != null)
{
// Pass call through to the user control.
MyUserControl control = sender as MyUserControl;
if (control != null)
{
control.UpdateIcon();
}
}
}
public void UpdateIcon()
{
BitmapImage replacementImage = new BitmapImage();
replacementImage.BeginInit();
replacementImage.CacheOption = BitmapCacheOption.OnLoad;
// Setting the URI does not throw an exception if the URI is
// invalid or if the file at the target URI is not an image.
// The BitmapImage class does not seem to provide a mechanism
// for determining if it contains valid data.
replacementImage.UriSource = new Uri(IconPath, UriKind.RelativeOrAbsolute);
replacementImage.EndInit();
// I tried this null check, but it doesn't really work. The replacementImage
// object can have a non-null UriSource and still contain no actual image.
if (replacementImage.UriSource != null)
{
myIcon.Source = replacementImage;
}
}
而這裏的如何我也許可以在另一個XAML文件中的這個用戶控件的實例:
<!--
My problem: What if example.png exists but is not a valid image file (or fails to load)?
-->
<MyUserControl IconPath="C:\\example.png" />
或者,也許有人可以建議一個不同的/更好的方式來在運行時加載圖像。謝謝。
的寬度和高度,我不認爲這些解決方案適用於我的情況,因爲我使用的URI指向本地文件(沒有什麼會通過HTTP)。我其實在第一個鏈接中嘗試瞭解決方案,並且拋出了一個異常,指出URI前綴未被識別。我使用的URI字符串的形式是:「pack:// application:,,,/ReferencedAssembly; component/ResourceFile.xaml」 – RobotNerd 2012-04-20 16:46:21
@RobotNerd您是否找到任何解決方案? – 2015-03-10 05:13:03