hej,
我不知道如何解决我的问题。我想从我的TextBox验证用户输入,然后如果输入错误则更改我的标签的颜色。我需要 验证我的Get和Set中的输入?或者这完全错了吗?
我的xaml代码:
<Label x:Name="lblEmail" Content="Email Adress" Foreground="{Binding EmailAdressValid}"/>
<TextBox x:Name="txtEmail" Text="{Binding EmailAdress, UpdateSourceTrigger=PropertyChanged}"/>
我的数据类:
public class MainData : INotifyPropertyChanged {
private int _emailAdress;
public int EmailAdress
{
get { return _emailAdress; }
set
{
_emailAdress = value;
OnPropertyChanged(nameof(EmailAdress));
}
}
private System.Windows.Media.Brush _emailAdressValid;
public System.Windows.Media.Brush EmailAdressValid
{
get { return _emailAdressValid; }
set
{
if(_emailAdress.Contains("@")) {
_emailAdressValid = Brushes.Black;
}
else {
_emailAdressValid = Brushes.Red;
}
OnPropertyChanged(nameof(EmailAdressValid));
}
}
}
答案 0 :(得分:1)
IMO您没有按照正确的方式在WPF中进行验证。我们IDataErrorInfo
就是这样。请将this视为首发。
现在回答你的问题,你的代码说它永远不会更新错误画笔,直到你set
它,你不会。实际上,您不需要EmailAdressValid
属性中的setter。在视图中提供电子邮件地址时,只需拨打OnPropertyChanged
即可。
public class MainData : INotifyPropertyChanged
{
private string _emailAdress;
public string EmailAdress
{
get { return _emailAdress; }
set
{
_emailAdress = value;
OnPropertyChanged(nameof(EmailAdress));
OnPropertyChanged(nameof(EmailAdressValid));
}
}
private System.Windows.Media.Brush _emailAdressValid;
public System.Windows.Media.Brush EmailAdressValid
{
get
{
if(_emailAdress.Contains("@"))
{
_emailAdressValid = Brushes.Black;
}
else
{
_emailAdressValid = Brushes.Red;
}
return _emailAdressValid;
}
}
}
答案 1 :(得分:0)
使用控件绑定功能直接将标签绑定到电子邮件输入文本框。然后使用值转换器验证电子邮件的值并返回所需的背景颜色。请参考以下代码以供参考:
<?php //connecting to the database define('DB_HOST', 'localhost'); define('DB_NAME', 'connected_car_1'); define('DB_USER','Maryam1'); define('DB_PASSWORD','telecom1213'); $con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); $db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error()); $sql = "INSERT INTO connected_car_1.sensor (value) VALUES ('".$_GET["value"]."')"; // Execute SQL statement mysql_query($sql,$con); mysql_close($con); ?>
Include this resource as static resource in xaml file and use in the binding as below
public class TextToBackgroundConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { // Validate the email text and retun background color of your choice } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { // Not needed } }