gpt4 book ai didi

c# - UpdateSourceTrigger 不工作?

转载 作者:行者123 更新时间:2023-11-30 22:20:42 27 4
gpt4 key购买 nike

我正在尝试在按下某个键时验证文本框中的文本。这是显示我正在尝试做的事情的最短代码示例:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox FontSize="15" HorizontalAlignment="Left" Name="txtEmail" VerticalAlignment="Top" Width="135"
Text="{Binding ValidationRules.EmailAddress, ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</Window>

“验证规则”类:

 class ValidationRules
{
string email = "";
public string EmailAddress
{
get
{
return email;
}

set
{
Console.WriteLine("Setting!");
//Only check if there is any text for now...
if (String.IsNullOrWhiteSpace(value))
{
throw new Exception();
}

email = value;
}
}

}

当我开始在文本框中键入内容时,即使我正在使用 UpdateSourceTrigger=PropertyChanged,我也没有将“Setting”作为控制台输出。我已经完成了研究,但我能找到的所有示例都很冗长且令人困惑。如果您能指出我在验证中遇到的任何其他错误,我也将不胜感激,但如果可能,请尝试用简单的术语进行解释,因为我是 WPF 的新手。

最佳答案

这一定是您在何处设置 DataContext 的问题。

这个例子似乎工作正常:

代码:

public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
ValidationRules = new ValidationRules();
}

private ValidationRules _validation;
public ValidationRules ValidationRules
{
get { return _validation; }
set { _validation = value; NotifyPropertyChanged("ValidationRules"); }
}


public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}

public class ValidationRules : INotifyPropertyChanged
{
string email = "";
public string EmailAddress
{
get
{
return email;
}

set
{
Console.WriteLine("Setting!");
//Only check if there is any text for now...
if (String.IsNullOrWhiteSpace(value))
{
throw new Exception();
}
email = value;
NotifyPropertyChanged("EmailAddress");
}
}

public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}

}

XAML

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication1.MainWindow"
Title="MainWindow" Height="125.078" Width="236.441" x:Name="UI" >
<Grid DataContext="{Binding ElementName=UI}">
<TextBox FontSize="15" HorizontalAlignment="Left" Name="txtEmail" VerticalAlignment="Top" Width="135"
Text="{Binding ValidationRules.EmailAddress, ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</Window>

关于c# - UpdateSourceTrigger 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14823119/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com