我有一個掙扎,我不知道如何設定畫布相對于 MVVM 的背景和大小,目前,我只在視圖部分處理這個,并且作業正常,在我想繪制的這個影像(畫布)上一些矩形,但我希望能夠根據 MVVM 模式做所有事情。
var bmp = new BitmapImage(new Uri(filename, UriKind.Relative));
ImageBrush brush = new ImageBrush();
brush.ImageSource = bmp;
canvas.Width = bmp.PixelWidth;
canvas.Height = bmp.PixelHeight;
canvas.Background = brush;
canvas.SnapsToDevicePixels = true;
uj5u.com熱心網友回復:
視圖模型可以公開一個屬性,例如影像檔案路徑
public string ImagePath { get; set; }
你會像這樣系結到它
<Canvas Width="{Binding Background.ImageSource.PixelWidth,
RelativeSource={RelativeSource Self}}"
Height="{Binding Background.ImageSource.PixelHeight,
RelativeSource={RelativeSource Self}}"
SnapsToDevicePixels="True">
<Canvas.Background>
<ImageBrush ImageSource="{Binding ImagePath}"/>
</Canvas.Background>
</Canvas>
string從to的轉換將由WPF 中ImageSource的實體自動執行。ImageSourceConverter
當視圖模型公開型別的屬性時,系結會更簡單BitmapSource:
public BitmapSource Image { get; set; }
XAML:
<Canvas Width="{Binding Image.PixelWidth}"
Height="{Binding Image.PixelHeight}"
SnapsToDevicePixels="True">
<Canvas.Background>
<ImageBrush ImageSource="{Binding Image}"/>
</Canvas.Background>
</Canvas>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/521973.html
標籤:C#wpf虚拟机
