如何在文本框中显示计时器? [英] How do I display timer in textbox?

查看:144
本文介绍了如何在文本框中显示计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



我是C#的新手,我对MVVM几乎没有疑问。何时使用IVauleConverter和绑定概念?为了理解这个概念,我写了一个小的演示项目。

实际上我正在尝试实现我的名字,姓氏,全名,计时器和椭圆的小项目。计时器文本框必须显示时间处理程序事件发生的时间和椭圆的颜色必须改变。我想分别为ui编写代码,逻辑必须不同。在下面的代码中,它没有在计时器文本框中显示时间。



我是什么尝试过:



Hello,

I am new to C#,i have few doubts regarding the MVVM. When to use the IVauleConverter and the binding concept? To understand the concept,I have written a small demo project.
Actually I am trying to implement the small project where i have first name ,last name,full name, timer and ellipse.The timer text box has to display the time when ever the time handler event arises and the color of ellipse has to change. I want to write code for ui separately and logic must be different.In the below code,Its not displaying the time in timer text box.

What I have tried:

private DispatcherTimer atimer;
        public Person personobj { get; set; }

       public MainWindow()
        {
            InitializeComponent();
            personobj = new Person();
            personobj.firstName = "hello";
            personobj.lastName= "";
           
            this.DataContext = personobj;
            // aTimer = new System.Timers.Timer(2000);
            // aTimer.Elapsed += new ElapsedEventHandler(OnTimeEvent);
            // aTimer.Enabled = true;
         //   atimer = new DispatcherTimer();
           // atimer.Interval = TimeSpan.FromMilliseconds(5000);
            //atimer.Tick += new EventHandler(OnTimeEvent);
            //atimer.Start();

        }

        /*private void OnTimeEvent(object sender, EventArgs e)
        {
            //TimerCount.Text = DateTime.Now.ToString("hh:mm:ss");
           // throw new NotImplementedException();
        }*/
    }

    public class Person : INotifyPropertyChanged
    {
        
        /// <summary>
        /// 
        /// 
        public String firstName;
        public String lastName;
        public String fullName="";
        private Boolean colorchange=false;
        private String timeIndicator;
        private DispatcherTimer timeCount;
        public Person()
        {
            timeCount = new DispatcherTimer();
            timeCount.Tick += new EventHandler(Timer_Tick);
            timeCount.Interval = TimeSpan.FromMilliseconds(5000);
            timeCount.Start();

        }
        public String FirstName
        {
            get
            {
                return firstName;
            }

            set
            {
                if (firstName != value)
                {
                    firstName = value;
                    OnPropertyChanged("FirstName");
                    OnPropertyChanged("FullName");
                }
            }
        }

        public String LastName
        {
            get
            {
                return lastName;
            }

            set
            {
                if (lastName != value)
                {
                    lastName = value;
                    OnPropertyChanged("LastName");
                    OnPropertyChanged("FullName");
                }
            }
        }

        public String FullName
        {
            get
            {
                //  Debug.WriteLine(fullName);
                return this.fullName = firstName + " " + lastName;

            }

            set
            {
                this.fullName = value;
                OnPropertyChanged("FullName");
                /*if (fullName != "")
                  {
                      colorchange = false;
                  }
                  else
                  {
                      colorchange = true;
                  }*/



                  }
            }


        public Boolean Colorchange
        {
            get
            {
                return colorchange;
            }

            set
            {
                colorchange = value;
                OnPropertyChanged("Colorchange");
            }
        }

        public string TimeIndicator
        {
            get
            {
                return timeIndicator;
            }

            set
            { 
                timeIndicator = value;
               if (timeIndicator != null)
                  {
                      colorchange = true;
                  }
                  else
                  {
                      colorchange = false;
                  }

                OnPropertyChanged("TimeIndicator");
            }
        }
      

        private void Timer_Tick(object sender, EventArgs e)
        {
            TimeIndicator = DateTime.UtcNow.ToString("hh:mm:ss");
        //    OnPropertyChanged("TimeIndicator");
        }
      //  public delegate PropertyChangedEventHandler(string property);
        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                 PropertyChanged(this, new PropertyChangedEventArgs(property));
        //        PropertyChanged(property);
            }
        }


    }
   // [ValueConversion(typeof(Person), typeof(Brush))]
    public class ColorChange : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
         //  Boolean BooleanValue = (Boolean)value;
         
            if (value.ToString()!= null)
            {

                return value.ToString();

            }
            else
            {
                return (object)Brushes.Green;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
           if (value is bool)
            {
                if ((bool)value == true)
                    return new SolidColorBrush(Colors.Green);
                else
                    return new SolidColorBrush(Colors.Red);
            }
            return null;
        }
    }
}







<window.resources>
        <local:ColorChange x:Key="ColorChange"/>
    
    <grid>
        
        <TextBox  Text="{Binding Path=FirstName, Mode=TwoWay}" Margin="145,20,187,264" />

        
        <TextBox  Text="{Binding  Path=LastName, Mode=TwoWay}" Margin="145,75,187,209" />
        
        <TextBox Name="fulltxtname" Text="{Binding Path=FullName, Mode=TwoWay}"  Margin="145,125,187,159"/>
      
        
        <TextBox Name ="TimerCount" Text="{Binding Path=timeIndicator,Mode=TwoWay }" Margin="75,200,297,89"/>
        <Ellipse Fill="{Binding ElementName=TimerCount, Converter={StaticResource ColorChange}}" HorizontalAlignment="Left" Height="35" Margin="260,195,0,0" Stroke="Black" VerticalAlignment="Top" Width="40"/>

推荐答案

这是一个如何设置它的演示(是的我不使用计时器,但同样的原则适用):



设置通知基础



封装公共代码。

Here is a demo of how to set it up (yes I don't use a timer, but the same principle applies):

Set up notification base


Encapsulate common code.
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WpfBindingEvents
{
    public abstract class ObservableObject : INotifyPropertyChanged
    {
        public void Notify([CallerMemberName] string caller = "")
        {
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(caller));

        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}



型号




Model


namespace WpfBindingEvents
{
    public class Person: ObservableObject
    {
        private string firstName;
        public string FirstName
        {
            get { return firstName; }
            set
            {
                firstName = value;
                Notify();
                SetFullName();
            }
        }

        private string lastName;
        public string LastName
        {
            get { return lastName; }
            set
            {
                lastName = value;
                Notify();
                SetFullName();
            }
        }

        private string fullName;
        public string FullName
        {
            get { return fullName; }
            private set
            {
                fullName = value;
                Notify();
            }
        }

        private void SetFullName()
        {
            FullName = firstName + " " + lastName;
        }
    }
}



ViewModel




ViewModel


namespace WpfBindingEvents
{
    public class MainViewModel : ObservableObject
    {

        public MainViewModel()
        {
            Model.PropertyChanged += ModelPropertyChanged;
        }

        private void ModelPropertyChanged(object sender, 
                                          PropertyChangedEventArgs e)
        {
            HasFullName = !string.IsNullOrEmpty(Model.FullName);
        }

        public Person Model { get; } = new Person();

        private bool hasFullName;
        public bool HasFullName
        {
            get { return hasFullName; }
            set
            {
                hasFullName = value;
                Notify();
            }
        }
    }
}



ValueConverter




ValueConverter


using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace WpfBindingEvents
{
    public class ValidationColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return new SolidColorBrush((bool)value ? Colors.Green : Colors.Red);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}



Xaml Page




Xaml Page


<Window x:Class="WpfBindingEvents.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:WpfBindingEvents"

        mc:Ignorable="d"

        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MainViewModel/>
    </Window.DataContext>
    <Window.Resources>
        <local:ValidationColorConverter x:Key="ValidationColorConverter"/>
    </Window.Resources>
    <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <TextBlock Text="First Name:" Margin="10 5"/>
        <TextBox Text="{Binding Model.FirstName, Mode=TwoWay, 
                                UpdateSourceTrigger=PropertyChanged}" 

                 Grid.Column="1" 

                 Width="200" VerticalAlignment="Center"/>

        <TextBlock Text="Last Name:" Grid.Row="1" Margin="10 5"/>
        <TextBox Text="{Binding Model.LastName, Mode=TwoWay, 
                                UpdateSourceTrigger=PropertyChanged}" 

                 Grid.Row="1" Grid.Column="1" 

                 Width="200" VerticalAlignment="Center"/>

        <TextBlock Text="Full Name:" Grid.Row="2" Margin="10 0"

                   VerticalAlignment="Center"/>
        <Border BorderThickness="1" 

                BorderBrush="{Binding HasFullName, 
                                      Converter={StaticResource ValidationColorConverter}}" 

                Margin="0 5" Grid.Row="2" Grid.Column="1"

                HorizontalAlignment="Stretch">
            <TextBlock Text="{Binding Model.FullName}" Grid.Row="1" Margin="5"/>
        </Border>
    </Grid>
</Window>


这篇关于如何在文本框中显示计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆