Reputation: 672
I have a WPF application following the MVVM architecture.
On one of the screens is a chart which needs to be saved as an image file on Save button click.
I can save the chart using the below code in code behind:
Rectangle rect = new Rectangle(0, 0, 100, 100);
Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
bmp.Save(fileName, ImageFormat.Jpeg);
But I need to be able to do this in my ViewModel.
For this purpose, I pass the ActualHeight & ActualWidth as the command parameters for the Click command of the button in below manner:
<Button Content="Save" Command="{Binding MyViewModel.SaveCommand">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource DimensionConverter}">
<Binding Path="ActualWidth" ElementName="MyChart"/>
<Binding Path="ActualHeight" ElementName="MyChart"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
In my converter:
public class DimensionConverter : IMultiValueConverter
{
public object Convert(object[] values, ...)
{
return values.Clone();
}
...
}
Then, in command execution logic:
public void OnExecute(object parameter)
{
var values = (object[])parameter;
var width = (double)values[0];
var height = (double)values[1];
...
}
But, I also need to be able to pass the co-ordinates of the Chart control wrt Origin. This can be done using PointToScreen method. But how can I pass them to the view model keeping in mind MVVM?
Or is there any other way that I can capture a region of a screen & save as image in MVVM architecture?
Upvotes: 3
Views: 797