WPF 中 UserControl作为另一个Process宿主到Window里, ErrorTemplate的默认红框没有出现

最近做WPF项目遇到一个问题, 我有2个process, 一个Process里只有Usercontrol, 另一个Process获取前一个Process中Usercontrol并host到当前的window里。 结果Usercontrol里的ErrorTemplate默认的红框没有出现, 但是ValidationRule已经触发。

原因找见: Window类默认的Style包含AdornerDecorator元素, 而UserControl没有。 主要是因为UserControl经常应用在Window里或者其他上下文已经有了AdornerLayer。


解决办法: 在UserControl的逻辑树的根下添加AdornerDecorator, 如:
<UserControl>
     <AdornerDecorator>
          <Grid Background="Yellow">
               ...
          </Grid>
     </AdornerDecorator>
</UserControl>

还需要把子控件的Margin设置下, 腾出空间显示ErrorTemplate。

There is no AdornerLayer in which the error template can be drawn.

Window's default style includes an AdornerDecorator, but UserControl's does not. That's because UserControls are frequently used inside a Window or some other context that already supplies an AdornerLayer.

In your case there is no surrounding AdornerLayer, so you need to add one explicitly. In PASimulationView.xaml:

<AdornerDecorator>
<Grid Background="Yellow">
...
</Grid>
</AdornerDecorator>

You might also want to add a Margin to the TextBox, or do something else to move it away from the top and left edges of the UserControl, so that the top and left edges of the error template are visible.

https://connect.microsoft.com/VisualStudio/feedback/details/725602/wpf-validationrule-has-been-trigged-but-the-textboxs-default-errortemplate-did-not-show-red-border 

你可能感兴趣的:(WPF)