我正在尝试验证WPF中的控件并在我设计的ControlTemplate中显示Exception消息,但是当我运行应用程序时,逻辑工作正常但不是在控件模板中看到Exception消息,应用程序会中断和抛出应该在ControlTemplate中显示的异常消息。我在下面发布我的代码,有人请告诉我我做错了什么。
MainWindow.xaml
<StackPanel>
<AdornerDecorator>
<TextBox Width="200" Margin="5" Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}" >
<TextBox.Text>
<Binding Path="Name" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" ValidatesOnExceptions="True" >
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</AdornerDecorator>
</StackPanel>
的App.xaml
<ControlTemplate x:Key="TextBoxErrorTemplate">
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Right"
Foreground="Orange"
FontSize="12pt"></TextBlock>
<Border BorderBrush="Green" BorderThickness="1">
<AdornedElementPlaceholder />
</Border>
</DockPanel>
</ControlTemplate>
Person.cs类
public class Person
{
private string _name;
public string Name {
get { return _name;}
set {
_name = value;
if (String.IsNullOrEmpty(_name))
{
throw new ApplicationException("Name is mandatory");
}
}
}
}
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
Person p = new Person();
p.Name="faisal";
this.DataContext = p;
}
不是在定义的Control模板中显示Exception消息,而是显示如下消息: