我有一個WPF .xaml文件,其中包含一個圖像框架元素綁定到我的C#代碼中的BitmapSource。目前,我很難編碼我的位圖的圖像寬度和高度(即512px),並且我已經指定了框架元素不要拉伸圖像。所以,如果我的窗口比位圖大,圖像似乎漂浮在窗口的邊界內。但是,我想要的是,位圖寬度和高度自動綁定到.xaml窗口的寬度和高度。所以,當我調整窗口大小時,位圖會隨着它調整大小。我不是簡單地希望圖像被「拉伸」......相反,我希望位圖的寬度和高度與包含它的窗口相匹配。我不完全確定如何做到這一點,但我會發布我迄今爲止的設置。WPF綁定圖像的寬度和高度與依賴屬性
以我的.xaml文件,我有圖片框架元件(注:渲染變換僅僅翻轉沿水平軸的圖像):
<Image Source="{Binding WpfPreview}" Name="VectorPreview" Stretch="None" Width="{Binding Xres}" Height="{Binding Yres}" RenderTransformOrigin="0.5,0.5">
<Image.RenderTransform>
<ScaleTransform ScaleY="-1"/>
</Image.RenderTransform>
</Image>
然後我的C#代碼中有以下代碼:
protected BitmapSource wpfPreview;
public BitmapSource WpfPreview
{
get { return wpfPreview; }
set
{
wpfPreview = value;
NotifyPropertyChanged("WpfPreview");
}
}
protected static int xres = 512;
public int Xres
{
get { return xres; }
set
{
xres = value;
NotifyPropertyChanged("Xres");
UpdateBitmapPreview();
}
}
protected static int yres = 512;
public int Yres
{
get { return yres; }
set
{
yres = value;
NotifyPropertyChanged("Yres");
UpdateBitmapPreview();
}
}
protected GDI.Bitmap gdiPreviewImage = new GDI.Bitmap(xres, yres);
public void UpdateBitmapPreview()
{
if(gdiPreviewImage.Width != xres || gdiPreviewImage.Height != yres) gdiPreviewSurface = new GDI.Bitmap(xres, yres);
using (var graphics = GDI.Graphics.FromImage(gdiPreviewImage))
{
graphics.Clear(Color.White);
graphics.ResetTransform();
currentSlicer.DrawBitmapPreview(graphics, PreviewOptions);
}
WpfPreview = Imaging.CreateBitmapSourceFromHBitmap(
gdiPreviewImage.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions()
);
}
將伸展設置爲填充。不需要綁定。 – Clemens