2016-05-19 69 views
0

我有一個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() 
      ); 
} 
+0

將伸展設置爲填充。不需要綁定。 – Clemens

回答

0

您基本上想要在調整大小的同時保持縱橫比嗎?我認爲這些屬性可以解決這個問題。將ClipToBounds設置爲true,並將Stretch設置爲Uniform

<Image Stretch="Uniform" ... 
+0

ClipToBounds在這裏沒有效果。 – Clemens

+0

@Clemens感謝您的信息。 –

-1

不過,我想的是,位圖的寬度和高度自動綁定到的.xaml窗口的寬度和高度。

因此,將寬度和高度直接綁定到窗口的寬度和高度並不簡單嗎?

<Image Source="{Binding WpfPreview}" 
     Stretch="None" 
     Width="{Binding Width, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 
     Height="{Binding Height, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />