我最终解决此类问题的方法是创建一个自定义用户控件来显示图像,它会在加载图像时自行调整大小。
这是我的xml:
<UserControl
x:Name="userControl"
x:Class="BoardsForWindows.Controls.BBPostImage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BoardsForWindows.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<StackPanel Orientation="Vertical">
<Image x:Name="imageViewer" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</StackPanel>
</UserControl>
这是我的 .xaml.cs(使用已删除的语句):
namespace BoardsForWindows.Controls
{
public sealed partial class BBPostImage : UserControl
{
private BitmapImage bitmapImage;
public string Source
{
get { return (string)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
// Using a DependencyProperty as the backing store for Source. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register("Source", typeof(string), typeof(BBPostImage), new PropertyMetadata(null, SourceChanged));
public BBPostImage()
{
this.InitializeComponent();
}
public static void SourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
BBPostImage image = d as BBPostImage;
if (image == null)
{
return;
}
string url = (e.NewValue ?? string.Empty).ToString();
Uri uri = null;
if (String.IsNullOrEmpty(url) || !Uri.TryCreate(url, UriKind.Absolute, out uri))
{
image.imageViewer.Width = 200;
image.imageViewer.Height = 40;
image.imageViewer.Source = null;
return;
}
image.bitmapImage = new BitmapImage();
image.bitmapImage.ImageFailed += image.bitmapImage_ImageFailed;
image.bitmapImage.ImageOpened += image.bitmapImage_ImageOpened;
image.bitmapImage.UriSource = uri;
image.imageViewer.Source = null;
image.imageViewer.Source = image.bitmapImage;
}
void bitmapImage_ImageOpened(object sender, RoutedEventArgs e)
{
Width = bitmapImage.PixelWidth;
Height = bitmapImage.PixelHeight;
}
void bitmapImage_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
// TODO
}
}
}