簡體   English   中英

WPF 和 C# 中帶 MVVM 的按鈕 model

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM