Ir ao conteúdo
  • Cadastre-se

C# Atualizar valor de TextBlock num documento XAML com C#


Joel Martins

Posts recomendados

Olá, Estou a tentar mudar o valor de texto de um bloco de texto de um documento XAML mas sem sucesso.
Código XAML atual:

        <TextBlock
            HorizontalAlignment="Left"
            Margin="198,86,0,0"
            TextWrapping="Wrap"
            Text="{Binding SetRecordStatusTxt}"
            VerticalAlignment="Top" Foreground="Red"/>

Código C# atual:

/*
 * 
 * 
 * 
 * 
 * ESTE FOI O ULTIMO
 * 
 * 
 * 
 * 
 */
using System;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Accord.vídeo.FFMPEG;
using AForge.vídeo;
using AForge.vídeo.DirectShow;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using Microsoft.Win32;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
using MessageBox = System.Windows.Forms.MessageBox;
using SaveFileDialog = System.Windows.Forms.SaveFileDialog;

namespace VideoRecorder
{
    internal class MainWindowViewModel : ObservableObject, IDisposable
    {
        #region Private fields

        private FilterInfo _currentDevice;

        private String _txtBox = "";
        private String _statTxt = "PAUSE";

        private BitmapImage _image;

        private IVideoSource _videoSource;
        private VideoFileWriter _writer;
        private bool _recording;
        private DateTime? _firstFrameTime;

        #endregion

        #region Constructor

        public MainWindowViewModel()
        {
            VideoDevices = new ObservableCollection<FilterInfo>();
            GetVideoDevices();
            StartRecordingCommand = new RelayCommand(StartRecording);
        }

        #endregion

        #region Properties

        public ObservableCollection<FilterInfo> VideoDevices { get; set; }
        public BitmapImage Image
        {
            get { return _image; }
            set { Set(ref _image, value); }
        }
        public FilterInfo CurrentDevice
        {
            get { return _currentDevice; }
            set { Set(ref _currentDevice, value); }
        }
        public string ValueText
        {
            get { return ""; }
            set { _txtBox = value; }
        }

        public string SetRecordStatusTxt
        {
            get { return _statTxt; }
            set { _statTxt = value; }
        }
        public ICommand StartRecordingCommand { get; private set; }

        public ICommand StopRecordingCommand { get; private set; }

        public ICommand StartSourceCommand { get; private set; }

        public ICommand StopSourceCommand { get; private set; }

        #endregion

        #region Full Program
        private void GetVideoDevices()
        {
            var devices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            foreach (FilterInfo device in devices)
            {
                VideoDevices.Add(device);
            }
            if (VideoDevices.Any())
            {
                CurrentDevice = VideoDevices[0];
                this.StartCamera();
            }
            else
            {
                MessageBox.Show("No webcam found");
            }
        }

        private void StartCamera()
        {
            if (CurrentDevice != null)
            {
                _videoSource = new VideoCaptureDevice(CurrentDevice.MonikerString);
                _videoSource.NewFrame += video_NewFrame;
                _videoSource.Start();
            }
            else
            {
                MessageBox.Show("Current device can't be null");
            }
        }

        private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            try
            {
                if (_recording)
                {
                    using (var bitmap = (Bitmap)eventArgs.Frame.Clone())
                    {
                        if (_firstFrameTime != null)
                        {
                            _writer.WriteVideoFrame(bitmap, DateTime.Now - _firstFrameTime.Value);
                        }
                        else
                        {
                            _writer.WriteVideoFrame(bitmap);
                            _firstFrameTime = DateTime.Now;
                        }
                    }
                }
                using (var bitmap = (Bitmap)eventArgs.Frame.Clone())
                {
                    var bi = bitmap.ToBitmapImage();
                    bi.Freeze();
                    Dispatcher.CurrentDispatcher.Invoke(() => Image = bi);
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show("Error on _videoSource_NewFrame:\n" + exc.Message, "Error", (MessageBoxButtons)MessageBoxButton.OK,
                    (MessageBoxIcon)MessageBoxImage.Error);
            }
        }

        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

        private void StatusTXT()
        {
            if (_recording == true)
            {
                _statTxt = "Recording...";
            }
            else
            {
                if (_recording == false)
                {
                    _statTxt = "PAUSE";
                }
            }
        }
        private void StartRecording()
        {

            if (_txtBox == "")
            {
                MessageBox.Show("Insert vídeo name please!");
                return;
            }
            _firstFrameTime = null;
            _writer = new VideoFileWriter();
            _writer.Open("C:\\Users\\SCHOOL ACCOUNT\\Videos\\trys\\" + _txtBox + ".avi", (int)Math.Round(Image.Width, 0), (int)Math.Round(Image.Height, 0));
            _recording = true;
            StatusTXT();
            timer.Interval = 5000; // here time in milliseconds 1000 milisegundos = 1 segundo
            timer.Tick += timer_Tick;
            timer.Start();
        }

        void timer_Tick(object sender, System.EventArgs e)
        {
            _recording = false;
            _writer.Close();
            _writer.Dispose();
            timer.Stop();
            _txtBox = "";
            StatusTXT();
        }

        public void Dispose()
        {
            if (_videoSource != null && _videoSource.IsRunning)
            {
                _videoSource.SignalToStop();
            }
            _writer?.Dispose();
        }
        #endregion
    }
}

Eu acho que o "problema" esteja nos getters e setters desta propriedade: "SetRecordStatusTxt";

e nesta classe "StatusTXT".

E o objetivo é sempre que a classe "StartRecording()" comece, chamar a classe StatusTXT e defenir o valor do campo TextBlock como "Recording..." e depois quando a classe TimerTick() for chamada defenir o valor do campo como "PAUSED".
image.png.46df4446549f867f30ae0c98f3c22d96.png

  • Amei 1
Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

 

GRÁTIS: ebook Redes Wi-Fi – 2ª Edição

EBOOK GRÁTIS!

CLIQUE AQUI E BAIXE AGORA MESMO!