gpt4 book ai didi

c# - 验证规则

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:48 24 4
gpt4 key购买 nike

在 wpf View 中,我有 3 个文本框,它们实现了这样的自定义验证规则:

<TextBox HorizontalAlignment="Left"
Height="30"
Grid.Row="2"
Grid.Column="1"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="150"
Validation.ErrorTemplate="{StaticResource ValidationTemplate}">
<TextBox.Text>
<Binding Path="Model.Age"
Mode="TwoWay"
UpdateSourceTrigger="PropertyChanged"
ValidatesOnExceptions="True"
ValidatesOnDataErrors="True">
<Binding.ValidationRules>
<validation:DataTypeValidationRules DataTypeRule="Required"
ErrorMessage="Required field" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>

我的问题是:如果我直接在文本框中更改文本,验证工作,如果文本框没有值,我可以看到我的模板,但如果我在 View 中什么都不做,然后单击我的保存按钮,它有一个命令绑定(bind)到我的 ViewModel,验证不起作用,因为我认为没有引发 OnPropertyChange 事件,所以我需要再次检查我的 ViewModel 中的值是否不为空,我不想这样做那个。

注意:我使用的是 MVVM 模式

抱歉我的英语不好,非常感谢您的回复。

最佳答案

我能想到的唯一可能发生此问题的方法是当文本是从 View 模型而不是从 UI 设置时,在这种情况下这确实是一个问题,因为不会重新评估验证规则。

要解决这个问题,您可以实现 IDataErrorInfo interface ,或者更好的是,INotifyDataErrorInfo interface (如果您的目标是 .NET 4.5)。这不仅可以解决您的问题,而且还是执行验证的 MVVM 方式(您目前正在 XAML 中定义验证逻辑,这并不好)。执行此操作后,您也可以从 XAML 中删除绑定(bind)规则。

实现示例:

public class ViewModel : IDataErrorInfo
{
public string Error
{
get { return null; }
}

public string this[string propertyName]
{
get
{
if (propertyName == "Age")
{
if (Age < 18)
{
return "Age must be at least 18.";
}
}

return null;
}
}
}

关于c# - 验证规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17434132/

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