当文本框的值传输到 MVVM[C#] 中的网格视图时,如何将文本框的值设置为空

本文关键字:文本 设置 视图 传输 值传 MVVM 网格 | 更新日期: 2023-09-27 18:36:16

我希望当单击"添加"按钮时,文本框值将传输到网格视图,文本框值将设置为空。如何实现这一点????

My View(XAML file)
<Window x:Class="EEEMVVM.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:helper="clr-namespace:EEEMVVM.Helper"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:mo="clr-namespace:EEEMVVM.Model"
    xmlns:vm="clr-namespace:EEEMVVM.View_Model" mc:Ignorable="d"
    Title="MainWindow" Height="387" Width="567">
<Window.Resources>
    <vm:ShowStudentInfo x:Key="ShowStudentInfo"/>
    <vm:NewStudentViewModelBase x:Key="NewStudentViewModelBase"/>
    <mo:Student x:Key="Student"/>
</Window.Resources>
<Grid Height="263" Width="476">
    <Grid.Resources>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <Trigger  Property="Validation.HasError" Value="true">
                    <Setter  Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}" />
                </Trigger>
            </Style.Triggers>
        </Style>

    </Grid.Resources>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="48*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="18*" />
    </Grid.ColumnDefinitions>
    <Label Height="28" Margin="0,7,0,0" HorizontalAlignment="Left"  Name="label1" VerticalAlignment="Top" Content="Name" />
    <TextBox Grid.Column="1" Grid.Row="0" Height="23" Margin="6,12,0,0" 
             HorizontalAlignment="Left" Name="txtbox_name" VerticalAlignment="Top"
             Width="120" 
             Text="{Binding Source={StaticResource NewStudentViewModelBase}, Path=StudentName,
                            Mode=TwoWay,
                            UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}"  />
    <Label   Grid.Column="2" Height="28" HorizontalAlignment="Left" Name="label2" VerticalAlignment="Top" Content="Roll No" Margin="0,10,0,0" Grid.RowSpan="2" />
    <TextBox Grid.Column="3" Grid.Row="0" Height="23" Margin="6,12,0,0" 
             HorizontalAlignment="Left" Name="txtbox_rollno" VerticalAlignment="Top" 
             Width="120" MaxLength="7" helper:TextBoxHelpers.IsNumeric="True"
             Text="{Binding Source={StaticResource NewStudentViewModelBase}, Path=StudentRollNo,
                            Mode=TwoWay,
                            UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}"  />
    <Label Grid.Row="1" Height="28" Margin="0,7,0,0" HorizontalAlignment="Left" Name="label3" VerticalAlignment="Top" Content="Email" />
    <TextBox Grid.Column="1" Grid.Row="1" Height="23" Margin="6,12,0,0" 
             HorizontalAlignment="Left" Name="txtbox_email" VerticalAlignment="Top" 
             Width="120"
             Text="{Binding Source={StaticResource NewStudentViewModelBase}, Path=StudentEmail,
                            Mode=TwoWay,
                            UpdateSourceTrigger=PropertyChanged,
                            ValidatesOnDataErrors=True}"/>
    <Label   Grid.Column="2" Grid.Row="1" Height="28" Margin="0,7,0,0" HorizontalAlignment="Left" Name="label4" VerticalAlignment="Top" Content="Contact No"/>
    <TextBox Grid.Column="3" Grid.Row="1" Height="23" Margin="6,12,0,0" 
             HorizontalAlignment="Left" Name="txtbox_contactno" VerticalAlignment="Top" 
             Width="120" MaxLength="10" helper:TextBoxHelpers.IsNumeric="True"
             Text="{Binding Source={StaticResource NewStudentViewModelBase}, Path=StudentContactNo,
                            Mode=TwoWay,
                            UpdateSourceTrigger=PropertyChanged,
                            ValidatesOnDataErrors=True}"/>
        <ListView ItemsSource="{Binding Source={StaticResource NewStudentViewModelBase}, Path=Students}" Grid.Row="3" Grid.ColumnSpan="6" Width="393" Margin="28,23,55,25" HorizontalAlignment="Center" Background="White" Height="60">
            <ListView.View >
                <GridView>
                <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Source={StaticResource NewStudentViewModelBase}, Path=StudentName}" Width="90"/>
                <GridViewColumn  Header="Roll No" DisplayMemberBinding="{Binding Source={StaticResource NewStudentViewModelBase}, Path=StudentRollNo}" Width="90"/>
                <GridViewColumn  Header="Email" DisplayMemberBinding="{Binding Source={StaticResource NewStudentViewModelBase}, Path=StudentEmail}" Width="90"/>
                <GridViewColumn  Header="Contact No" DisplayMemberBinding="{Binding Source={StaticResource NewStudentViewModelBase}, Path=StudentContactNo}" Width="90"/>
            </GridView>
            </ListView.View>
        </ListView>

    <Button Command="{Binding Source={StaticResource NewStudentViewModelBase}, Path=InsertDataCommand}" IsEnabled="{Binding IsValidSave}" Grid.Column="1" Grid.Row="4" Content="Add" Height="26" Margin="37,30,20,11" Name="button1" Width="75"  />
    <Button Content="Submit" Grid.Column="3" Grid.Row="4" Height="23" HorizontalAlignment="Left" Margin="24,33,0,0" Name="button2" VerticalAlignment="Top" Width="75" />
</Grid>

我的视图模型:此类包含将数据从文本框传输到网格视图的验证传输。

  namespace EEEMVVM.View_Model
     {
     class NewStudentViewModelBase:INotifyProperty,IDataErrorInfo
     {
    #region Fields        
      private Dictionary<string, bool> validProperties;
      private Student _student;
      private ObservableCollection<Student> _students;
      private RelayCommand _insertDataCommand;
      public string studentRollNo;
      public string studentName;
      public string studentEmail;
      public string studentContactNo;
      private Regex emailRegex = new Regex(@"^((['w-]+'.)+['w-]+|([a-zA-Z]{1}|['w-]{2,}))@"+@"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])'.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])'."+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])'.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"+ @"([a-zA-Z]+['w-]+'.)+[a-zA-Z]{2,4})$");
      private Regex nameRegex = new Regex("[^0-9]+");
      private static readonly char[] IllegalCharacters = new char[] { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '+', '=', '{', '}', '[', ']', '/', ':', '>', '<', '?', '''', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    #endregion
    #region Constructor
      public NewStudentViewModelBase()
      {
            this.validProperties = new Dictionary<string, bool>();
            this.validProperties.Add("StudentRollNo", false);
            this.validProperties.Add("StudentName", false);
            this.validProperties.Add("StudentEmail", false);
            this.validProperties.Add("StudentContactNo", false);
      }
    #endregion
    public ObservableCollection<Student> Students
    {
        get
        {
            return _students;
        }
        set
        {
            _students = value;
            NotifyPropertyChanged("Students");
        }
    }


    #region Properties
    public string StudentRollNo
    {
        get { return studentRollNo; }
        set { studentRollNo = value; NotifyPropertyChanged("StudentRollNo"); }
    }
    public string StudentName
    {
        get { return studentName; }
        set { studentName = value; NotifyPropertyChanged("StudentName"); }
    }
    public string StudentEmail
    {
        get { return studentEmail; }
        set { studentEmail = value; NotifyPropertyChanged("StudentEmail"); }
    }
    public string StudentContactNo
    {
        get { return studentContactNo; }
        set { studentContactNo = value; NotifyPropertyChanged("StudentContactNo"); }
    }
    #endregion
    /* Enabling & Disabling the submit button */
    private bool isValidSave = false;
    public bool IsValidSave
    {
        get
        {
            return isValidSave;
        }
        set
        {
            isValidSave = value;
            NotifyPropertyChanged("IsValidSave");
        }
    }
    public Student Student
    {
        get
        {
            return _student;
        }
        set
        {
            _student = value;
            NotifyPropertyChanged("Student");
        }
    }
    public ICommand InsertDataCommand
    {
        get
        {
            if (_insertDataCommand == null)
                _insertDataCommand = new RelayCommand(param => this.Save(), param => this.IsValidSave);
            return _insertDataCommand;
        }
    }        
    public void Save()
    {
        Student = new Student();
        Students = new ObservableCollection<Student>();
        Students.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Students_CollectionChanged);
        Students.Add(Student);
        Student = new Student();
    }
    void Students_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        NotifyPropertyChanged("Students");
    }

    public string Error
    {
        get { throw new NotImplementedException(); }
    }
    public string this[string columnName]
    {
        get
        {   IsValidSave = false;
            string error = null;
            switch (columnName)
            {
                case "StudentName":
                    error = ValidateName();
                    validProperties["StudentName"] = error == string.Empty;
                    break;
                case "StudentRollNo":
                    error = ValidateRollno();
                    validProperties["StudentRollNo"] = error == string.Empty;
                    break;
                case "StudentEmail":
                    error = ValidateEmail();
                    validProperties["StudentEmail"] = error == string.Empty;
                    break;
                case "StudentContactNo":
                    error = ValidateContactNo();
                    validProperties["StudentContactNo"] = error == string.Empty;
                    break;
                default:
                    throw new ApplicationException("Unknown Property being validated on Product.");
            }
            if (validProperties["StudentName"] == true && validProperties["StudentRollNo"] == true && validProperties["StudentEmail"] == true && validProperties["StudentContactNo"] == true)
                this.IsValidSave = true;
            else
                this.IsValidSave = false;
            return error;
        }
    }

    private string ValidateContactNo()
    {
        long num;
        bool res = long.TryParse(StudentContactNo, out num);
        if (String.IsNullOrEmpty(this.StudentContactNo))
            return "Invalid! Contact Number needs to be entered!";
        if (this.StudentContactNo.Length < 10)
            return "Invalid! Contact Number must be of 10 digits!";
        if (this.StudentContactNo.Length > 10)
            return "Invalid! Contact Number should not be greater than 10 digits!";
        if (!(res))
            return "Invalid! Contact Number must contain digits!";
        else
            return String.Empty;
    }
    private string ValidateEmail()
    {
        if (String.IsNullOrEmpty(this.StudentEmail))
            return "Invalid! Student Email needs to be entered.";
        if(!IsValidEmailAddress)
            return "Invalid! Student Email needs to be valid.";
        else
            return String.Empty;
    }
    private bool IsValidEmailAddress
    {
        get
        {
            return emailRegex.IsMatch(StudentEmail);
        }
    }

    private string ValidateRollno()
    {
        if (String.IsNullOrEmpty(this.StudentRollNo))
            return "Invalid! Student Name needs to be entered.";
        if (this.StudentRollNo.IndexOfAny(IllegalCharacters) > 0)
            return "Invalid! Student Roll No should contain Alphabets only!";
        if (this.StudentRollNo.Length < 7 )
            return "Invalid! Student Roll No should have more than 8 letters!";
        else
            return String.Empty;
    }
    private string ValidateName()
    {
        if (String.IsNullOrEmpty(this.StudentName))
            return "Invalid! Student Name needs to be entered.";
        if (!IsValidName)
            return "Invalid! Student Name contain only Alphabets!!!";
        if (this.StudentName.IndexOfAny(IllegalCharacters) > 0)
            return "Invalid! Student Name should contain Alphabets only!";
        if (this.StudentName.Length < 6)
            return "Invalid! Student Name should have more than 6 letters!";
        else
            return String.Empty;
    }
    private bool IsValidName
    {
        get { return nameRegex.IsMatch(StudentName) ;}
    }
}

}

型:

namespace EEEMVVM.Model
{
class Student:INotifyProperty
{
    public string StudentRollNo
    {
        get; set;
    }
    public string StudentName
    {
        get; set;
    }
    public string StudentEmail
    {
        get; set;
    }
    public string StudentContactNo
    {
        get; set;
    }

    public void Save()
    {
    }
}

}

当文本框的值传输到 MVVM[C#] 中的网格视图时,如何将文本框的值设置为空

你的 InsertDataCommand 应该是这样的:

private RelayCommand _insertDataCommand;
    public RelayCommand InsertDataCommand
    {
        get
        {
            return _insertDataCommand
                   ?? (_insertDataCommand = new RelayCommand(
                       () =>
                       {
                           Students.Add(new Student
                           {
                               StudentRollNo = this.StudentRollNo,
                               StudentName = this.StudentName,
                               StudentEmail = this.StudentEmail,
                               StudentContactNo = this.StudentContactNo
                           });
                           StudentRollNo = String.Empty;
                           StudentName = String.Empty;
                           StudentEmail = String.Empty;
                           StudentContactNo = String.Empty;
                       }));
        }
    }

由于 Students 属性是一个ObservableCollection(这意味着实现INotifyCollectionChanged更改的将出现在 UI 中,而无需触发或设置任何其他内容),并且对于其他四个属性,将其值设置为 String.Empty 将触发 NotifyPropertyChanged 方法,更改也将传播到 UI