我是 WPF 的新手,我需要验证 ViewModel 中提到的那些属性,我怎么能以最简单的方式做到这一点?有人可以帮忙吗?任何方式我都可以在 MVVM 中做到这一点。我确实尝试过使用 XAML 模板,但我也无法使用多个控件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using FeedbackForm.Model;
using System.Windows.Input;
using System.Windows;
using System.Windows.Controls;
using MySql.Data.MySqlClient;
using System.ComponentModel.DataAnnotations;
namespace FeedbackForm.ViewModel
{
class MainViewModel:INotifyPropertyChanged
{
static int i = 1;
public data domObject;
public ICommand _SubmitCmd{get;set;}
public ICommand _ResetCmd{get;set;}
public Connection con;
public MainViewModel()
{
domObject= new data();
_SubmitCmd = new DelegateComand.DelegateCommand(OnSubmit);
_ResetCmd = new DelegateComand.DelegateCommand(OnReset);
}
public class EmailValidationAttribute : RegularExpressionAttribute
{
public EmailValidationAttribute()
: base(@"^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-zA-Z0-9]{1}[a-zA-Z0-9\-]{0,62}[a-zA-Z0-9]{1})|[a-zA-Z])\.)+[a-zA-Z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$")
{
}
}
public string Fname
{
get
{return domObject.fname ;}
set
{
domObject.fname =value ;
OnPropertyChanged("Fname");
}
}
public string Lname
{
get
{ return domObject.lname; }
set
{
domObject.lname = value;
OnPropertyChanged("Lname");
}
}
public bool Gender
{
get
{ return domObject.gender; }
set
{
domObject.gender = value;
OnPropertyChanged("Gender");
}
}
public decimal Contact
{
get
{ return domObject.contact ; }
set
{
domObject.contact = value;
OnPropertyChanged("Contact");
// try
// {
// //int.Parse(Contact);
// Convert.ToInt32(Contact);
// }
// catch (Exception ex)
//{
// throw new ApplicationException("Invalid Number");
//}
}
}
[EmailValidation(ErrorMessage = "Not in proper format")]
public string Email
{
get
{ return domObject.email; }
set
{
domObject.email = value;
OnPropertyChanged("Email");
}
}
public string Address
{
get
{ return domObject.address ; }
set
{
domObject.address = value;
OnPropertyChanged("Address");
}
}
public string Query
{
get
{ return domObject.query ; }
set
{
domObject.query = value;
OnPropertyChanged("Query");
}
}
public string Comment
{
get
{ return domObject.comment ; }
set
{
domObject.comment = value;
OnPropertyChanged("Comment");
}
}
private void OnReset(object obj)
{
ResetAll(this );
}
private void OnSubmit(object obj)
{ char g;
con = new Connection();
try{
if (domObject.gender == false)
{
g = 'M';
}
else
{
g = 'F';
}
con.command.CommandText = "Insert into tblfeedback(fname,lname,gender,email,contact_no,Address) values('" + domObject.fname + "','" + domObject.lname + "','" + g + "','" + domObject.email + "','" + domObject.contact + "','" + domObject.address + "')";
con.command.ExecuteNonQuery();
con.command.CommandText = "Insert into comment (query,comment,date)values('" + domObject.query + "','" + domObject.comment + "','" +( DateTime.Today.ToShortDateString().ToString())+ "')";
con.command.ExecuteNonQuery();
i++;
ResetAll(this);
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex);
}
}
public void ResetAll(object obj)
{
Fname = String.Empty;
Lname = String.Empty;
Gender = false;
Contact = 0;
Address = String.Empty;
Query = String.Empty;
Comment = String.Empty;
Email = String.Empty;
}
#region INotifyPropertyChanged Members
/// <summary>
/// Event to which the view's controls will subscribe.
/// This will enable them to refresh themselves when the binded property changes provided you fire this event.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// When property is changed call this method to fire the PropertyChanged Event
/// </summary>
/// <param name="propertyName"></param>
public void OnPropertyChanged(string propertyName)
{
//Fire the PropertyChanged event in case somebody subscribed to it
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
Following Xaml contains the Template which I used to validate contact property but I want to validate my Email by any means. I am new to WPF so I just want to know how can I use Regular Expression or anything to do that???
<Window x:Class="FeedbackForm.View.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="490.602" Width="549.249">
<Window.Resources>
<ControlTemplate x:Key="ValidationTemplate">
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Right"
Foreground="Red"
FontSize="12pt" Text="{Binding [0].ErrorContent}">
</TextBlock>
<Border BorderBrush="Red" BorderThickness="1">
<AdornedElementPlaceholder />
</Border>
</DockPanel>
</ControlTemplate>
</Window.Resources>
<DockPanel Background="Aquamarine">
<Grid Margin="0,25,0,-25">
<Grid.RowDefinitions>
<RowDefinition Height="51*" />
<RowDefinition Height="47*" />
<RowDefinition Height="44*" />
<RowDefinition Height="48*" />
<RowDefinition Height="61*" />
<RowDefinition Height="74*" />
<RowDefinition Height="64*" />
<RowDefinition Height="72*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions >
<ColumnDefinition Width="Auto" MinWidth="130"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Content="First Name" Grid.Column="0" HorizontalAlignment="Left" Margin="10,4,0,0" VerticalAlignment="Top" Height="26" Width="67"/>
<Label Content="Gender" Grid.Column="0" HorizontalAlignment="Left" Margin="10,2,0,0" Grid.Row="1" VerticalAlignment="Top" Height="26" Width="49"/>
<Label Content="E-mail" Grid.Column="0" HorizontalAlignment="Left" Margin="10,5,0,0" Grid.Row="2" VerticalAlignment="Top" Height="26" Width="43"/>
<Label Content="Contact" Grid.Column="0" HorizontalAlignment="Left" Margin="11,5,0,0" Grid.Row="3" VerticalAlignment="Top" Height="26" Width="51"/>
<Label Content="Address" Grid.Column="0" HorizontalAlignment="Left" Margin="9,4,0,0" Grid.Row="4" VerticalAlignment="Top" Height="26" Width="53"/>
<Label Content="Query" Grid.Column="0" HorizontalAlignment="Left" Margin="10,3,0,0" Grid.Row="5" VerticalAlignment="Top" Height="26" Width="42"/>
<Label Content="Comment" Grid.Column="0" HorizontalAlignment="Left" Margin="10,3,0,0" Grid.Row="6" VerticalAlignment="Top" Height="26" Width="62"/>
<Label Content="Last Name" Grid.Column="1" HorizontalAlignment="Left" Margin="162,7,0,0" VerticalAlignment="Top" Height="26" Width="66"/>
<Button x:Name="submit" Command="{Binding Path=_SubmitCmd}" Content="Submit" HorizontalAlignment="Left" Margin="17,10,0,0" Grid.Row="7" VerticalAlignment="Top" Width="75" Height="22" Grid.Column="1" Click="submit_Click"/>
<Button x:Name="reset" Content="Reset" HorizontalAlignment="Left" Margin="162,10,0,0" Grid.Row="7" VerticalAlignment="Top" Width="75" Grid.Column="1" Height="22" Command="{Binding _ResetCmd}"/>
<TextBox x:Name="txtfname" HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Grid.Column="1" Text="{Binding Fname}" TabIndex="1"/>
<TextBox x:Name="txtlname" HorizontalAlignment="Left" Height="23" Margin="262,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Grid.Column="1" TabIndex="2">
<Binding Path="Lname"></Binding>
</TextBox>
<RadioButton x:Name="rdfemale" Content="FEMALE" GroupName="grp1" IsChecked="{Binding Gender, Mode=TwoWay}" HorizontalAlignment="Left" Margin="130,12,0,0" Grid.Row="1" VerticalAlignment="Top" Grid.Column="1" Height="16" Width="82"/>
<RadioButton x:Name="rdmale" Content="MALE" GroupName="grp1" HorizontalAlignment="Left" Margin="10,12,0,0" Grid.Row="1" VerticalAlignment="Top" Grid.Column="1" Height="16" Width="82" />
<TextBox x:Name="txtemail" HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" Grid.Row="2" TextWrapping="Wrap" VerticalAlignment="Top" Width="191" Grid.Column="1" TabIndex="3">
<TextBox.Text>
<Binding Path="Email" Mode="TwoWay">
</Binding>
</TextBox.Text>
</TextBox>
<TextBox x:Name="txtcontact" Validation.ErrorTemplate="{StaticResource ValidationTemplate}" HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" Grid.Row="3" TextWrapping="Wrap" VerticalAlignment="Top" Width="191" Grid.Column="1" TabIndex="4">
<TextBox.Text>
<Binding Path="Contact" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<ExceptionValidationRule></ExceptionValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<RichTextBox x:Name="rtxtquery" SpellCheck.IsEnabled="True" HorizontalAlignment="Left" Height="38" Margin="10,23,0,0" Grid.Row="5" VerticalAlignment="Top" Width="276" RenderTransformOrigin="0.4,0.413" Grid.Column="1" TabIndex="6" >
<FlowDocument>
<Paragraph>
<Run Text="{Binding Query}"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
<RichTextBox x:Name="rtxtadd" HorizontalAlignment="Left" Height="38" Margin="10,10,0,0" Grid.Row="4" VerticalAlignment="Top" Width="276" RenderTransformOrigin="0.4,0.413" Grid.Column="1" TabIndex="5">
<FlowDocument>
<Paragraph>
<Run Text="{Binding Address}"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
<RichTextBox Grid.Column="1" SpellCheck.IsEnabled="True" HorizontalAlignment="Left" Height="44" Margin="10,10,0,0" Grid.Row="6" VerticalAlignment="Top" Width="276" TabIndex="7">
<FlowDocument>
<Paragraph>
<Run Text="{Binding Comment}"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
</Grid>
</DockPanel>
</Window>