I am trying to create a button in WPF with MVVM model using C# that takes a picture when pressed and saves it to the specified path. What I'm basically doing is creating a button that when pressed, it orders a camera to take a picture and receives the image back (through an api Rest), which is later saved as a .jpg image to a specified path (specified in code below). I have done this without the MVVM model and it works perfectly, but I need to do it using MVVM model and I seem to be doing something wrong, because it is not working.
Here is my code:
XAML code (View): `
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<TextBlock x:Name="instrucciones" Text="Press button" FontSize="30" Margin="50" TextAlignment="Center"/>
<Button Content="Tomar Foto" Command="{Binding TakePhotoCommand}" Margin="5 0 5 5" Width="200" FontSize="25" Padding="15 3"/>
</StackPanel>
</Grid>
</Window>
`
C# Code (ViewModel): `
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TakePhotoCommand = new RelayCommand(TakePhoto);
}
public void TakePhoto()
{
var request =(HttpWebRequest)WebRequest.Create("http://myIp port/TakePicture");
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
try
{
using (WebResponse response = request.GetResponse())
{
using (Stream strReader = response.GetResponseStream())
{
StreamReader reader = new StreamReader(strReader);
Bitmap bitmap = new Bitmap(strReader);
bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
bitmap.Save("C:\\path name.jpg", ImageFormat.Jpeg);
}
}
}
catch (WebException ex)
{
MessageBox.Show(ex.ToString());
}
}
public ICommand TakePhotoCommand { get; set; }
}
`
Already described in question
CodePudding user response:
First you are not using a MVVM pattern, you use MainWindow code-behind directly.
In your code you have to set the DataContext to this
in the class constructor.
public MainWindow()
{
InitializeComponent();
TakePhotoCommand = new RelayCommand(TakePhoto);
DataContext = this;
}