我正在尝试在WPF中使用文本框进行验证。问题是当没有数据输入文本框时会导致验证错误,没有显示validataion错误。有人可以给我一些帮助吗?先感谢您。这是我的代码
public class User
{
private string _name;
public string myName
{
get { return _name; }
set
{
_name = value;
if (String.IsNullOrEmpty(value))
{
throw new ApplicationException("User name is mandatory.");
}
}
}
}
<TextBox Height="23"
HorizontalAlignment="Right"
Margin="0,0,194,250" Name="textBox1"
VerticalAlignment="Bottom"
Width="120" >
<TextBox.Text>
<Binding Path="myName" >
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
编辑:我确实遇到了绑定问题。我修复了我的代码,这里是: 我开始创建用户和错误模板:
<local:User x:Key="myDataSource" myName="Enter Name" />
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="20">!!!</TextBlock>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
如果存在验证错误,我会禁用保存按钮
<Button Content="Write Kml"
Height="23"
HorizontalAlignment="Right"
Margin="0,0,12,41"
Name="writeKml"
VerticalAlignment="Bottom"
Width="75" Click="button2_Click" >
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="IsEnabled" Value="false" />
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=textBox1, Path=(Validation.HasError)}" Value="false">
<Setter Property="IsEnabled" Value="true" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
然后我修复了textBox以允许正确的验证
<TextBox Height="23"
HorizontalAlignment="Right"
Margin="0,0,194,250"
Name="textBox1"
VerticalAlignment="Bottom"
Validation.ErrorTemplate="{StaticResource validationTemplate}"
Width="120" >
<TextBox.Text>
<Binding
Source="{StaticResource myDataSource}"
Path="myName"
UpdateSourceTrigger="PropertyChanged"
ValidatesOnExceptions="True"
ValidatesOnDataErrors="True" >
<Binding.ValidationRules>
<local:CheckName />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
这是背后的代码
public class User
{
private string _name;
public string myName
{
get { return _name; }
set { _name = value; }
}
}
public class CheckName : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value == null || object.Equals(value, string.Empty))
{
return new ValidationResult(false, "Please enter user name");
}
if (value.ToString() == "Enter Name")
{
return new ValidationResult(false, "Please enter user name");
}
return new ValidationResult(true, null);
}
}
最后我将代码添加到窗口加载的例程中以强制验证
private void Window_Loaded(object sender, RoutedEventArgs e)
{
textBox1.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
我希望这有助于任何试图在WPF中验证文本框的人。
答案 0 :(得分:2)
您的User类需要实现INotifyPropertyChanged才能在WPF中支持数据绑定。您可能需要对WPF和数据绑定进行一些阅读,因为它是构建WPF(或Silverlight)应用程序所需的基础知识。
情侣链接让您入门: