[英]Button with MVVM model in WPF and C#
我正在尝试使用 C# 在 WPF 中使用 MVVM model 创建一个按钮,按下时拍照并将其保存到指定路径。 我基本上在做的是创建一个按钮,当按下该按钮时,它会命令相机拍照并接收回图像(通过 api Rest),稍后将其作为 a.jpg 图像保存到指定路径(在中指定)下面的代码)。 我在没有 MVVM model 的情况下完成了此操作,并且效果很好,但是我需要使用 MVVM model 来完成此操作,但我似乎做错了什么,因为它不起作用。
这是我的代码:
XAML 代码(查看):`
<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# 代码(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; }
}
`
已经在问题中描述
首先,您没有使用 MVVM 模式,而是直接使用 MainWindow 代码隐藏。
在您的代码中,您必须在 class 构造函数中将 DataContext 设置this
。
public MainWindow()
{
InitializeComponent();
TakePhotoCommand = new RelayCommand(TakePhoto);
DataContext = this;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.