実行時に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" />
または、誰かが、実行時に画像をロードする別の/より良い方法を提案するかもしれません。ありがとう。
の幅と高さを持っているだろうことがわかりましたファイル(何もHTTP経由ではありません)。私は実際にあなたの最初のリンクで解決策を試しました、そして、URIプレフィックスが認識されなかったという例外を投げました。私が使用しているURI文字列の型は、 "pack:// application:,,,/ReferencedAssembly; component/ResourceFile.xaml"という形式です。 – RobotNerd
@RobotNerd解決策は見つかりましたか? –