目前我的应用程序有一个窗口,其中有多个TextBox,CheckBox等,接收用户数据输入。但需要验证用户数据。由于用户需要输入什么样的数据是不确定的,因此我可能需要以编程方式添加额外的控件。
以下是我的简短演示:
<Window x:Class="WpfApplication7.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>
<Label Content="Don't care" HorizontalAlignment="Left" Margin="10,12,0,0" VerticalAlignment="Top" Height="23" Width="78"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="93,16,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="414"/>
<Label Content="Important1*" HorizontalAlignment="Left" Margin="10,40,0,0" VerticalAlignment="Top" Height="23" Width="78"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="93,44,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="414"/>
<Label Content="Importtant2*" HorizontalAlignment="Left" Margin="10,68,0,0" VerticalAlignment="Top" Height="23" Width="78"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="93,72,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="414"/>
<Label Content="Reserved for Programmatically added." HorizontalAlignment="Left" Margin="10,96,0,0" VerticalAlignment="Top" Height="188" Width="497"/>
<Button Content="Submit" HorizontalAlignment="Left" Margin="432,0,0,10" VerticalAlignment="Bottom" Width="75"/>
</Grid>
</Window>
请注意Don't care
在这种情况下无需验证。
对每个人都有效,我实施了ValidationRule
,以便自动完成。但是,当用户按下提交按钮时,我需要知道是否所有数据都已经过验证,这样我就可以确保用户做得很好。(或者如果并非所有用户数据都经过验证,则可能会禁用该按钮)
所以我的问题是,是否有任何干净的方式让我验证对我来说很重要的所有字段(在这种情况下,后跟*
)?请注意,以编程方式添加的控件也可能绑定到重要字段。
更新:
为什么我不在xaml中做所有事情? (绑定,验证)
因为每次窗口都会在不同的对象上工作,而且这个对象将具有哪些字段是不确定的。所以我必须相应地绑定和验证数据。因此,我的演示中有Reserved for Programmatically added.
。
我验证的方式是
BindingOperations.GetBinding(textbox, TextBox.TextProperty).ValidationRules.Add(new PositiveIntegerValidate());
其中:
public class PositiveIntegerValidate : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
int i;
if (!int.TryParse((string)value, out i))
return new ValidationResult(false, "Not Integer.");
if (i <= 0)
return new ValidationResult(false, "Less than or equal to 0.");
else
return new ValidationResult(true, null);
}
}
验证整数字段。
我有其他验证规则,但它无关紧要。