WPF MVVM制作发送短信小按钮

2019-12-30 14:41:49王旭

二、XAML页面代码


<Grid>
    <Grid.RowDefinitions>
      <RowDefinition/>
      <RowDefinition/>
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
      <Label Content="手机号"/>
      <TextBox Text="{Binding PhoneNum}" Height="20" Width="100"/>
      <Button Content="{Binding Src.BtnContent}" IsEnabled="{Binding Src.BtnIsEnable}" Command="{Binding SendCode}" Height="20" Width="120"/>
    </StackPanel>
    <StackPanel Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
      <Label Content="验证码"/>
      <TextBox Text="{Binding IdentifyCode}" Height="20" Width="100"/>
      <Button Content="提交" Command="{Binding Submit}" Height="20" Width="120"/>
    </StackPanel>
  </Grid>

三、VM页面代码  

  VM页面没有什么特别的,就是声明了一些字段,

  特别注意的是,由于前台的XAML页面上的发送短信按钮是需要倒计时的,因此Button的Content和IsEnable需要绑定到SendRandomCode这个类上,所以需要在VM下声明一下这个类 

 


public class BingVM: ViewModelBase
  {
    #region 界面字段
    private string phoneNum;//手机号
    private string identifyCode;//验证码
    public string PhoneNum
    {
      get
      {
        return phoneNum;
      }

      set
      {
        phoneNum = value;
        RaisePropertyChanged("PhoneNum");
      }
    }

    public string IdentifyCode
    {
      get
      {
        return identifyCode;
      }

      set
      {
        identifyCode = value;
        RaisePropertyChanged("IdentifyCode");
      }
    }
    #endregion

    #region 为获取验证码按钮设置content和isEnable用的
    SendRandomCode src = new SendRandomCode();
    public SendRandomCode Src
    {
      get { return src; }
      set
      {
        src = value;
      }
    }
    #endregion

    private RelayCommand sendCode;//获取验证码

    public RelayCommand SendCode
    {
      get
      {
        return sendCode ?? (sendCode = new RelayCommand(
          () =>
          {
            if (!string.IsNullOrEmpty(PhoneNum))
            {
              src.GetCode(PhoneNum);
            }
            else
            {
              MessageBox.Show("手机号不能为空!");
            }

          }));
      }
    }
    private RelayCommand submit;

    public RelayCommand Submit
    {
      get
      {
        return submit ?? (submit = new RelayCommand(
          () =>
          {
            if (IdentifyCode == src.IdCode && PhoneNum == src.PhoneNum)
            {
              MessageBox.Show("验证成功");
            }
            else
            {
              MessageBox.Show("验证失败");
            }
          }));
      }
    }

  }