gpt4 book ai didi

带有验证的 WPF 文本框丢失 ErrorTemplate

转载 作者:行者123 更新时间:2023-12-04 18:29:26 25 4
gpt4 key购买 nike

我有一个与这些非常相似的问题:

Issue with WPF validation(IDataErrorInfo) and tab focusing

TextBox with validation loses ErrorTemplate on tab change
AdornerDecorator做这个把戏在同一个实例中Window ,但当 Window重新加载,我切换到 TabItem包含 TextBox错误地,ErrorTemplate不会再出现了。

<Window x:Class="Views.MyWindowView">
<Grid>

<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>

<TabControl HorizontalAlignment="Stretch"
Height="Auto"
VerticalAlignment="Top"
Width="Auto"
SelectionChanged="TabItemChanged"
Name="MyTabControl">

<!-- Below, AdornerDecorator are added for the following reason:
the Validation.Error cues are painted in the Adorner Layer.
When tabs are switched, that layer is discarded. -->

<!-- The view 1 tab.-->
<TabItem Header="{Resx tab1_Header}"
Name="Tbi1">
<AdornerDecorator>
<vw:MyView1 DataContext="{Binding}"/>
</AdornerDecorator>
</TabItem>

<!-- The view 2 tab.-->
<TabItem Header="{Resx tab2_Header}"
Name="Tbi2">
<AdornerDecorator>
<vw:MyView2 DataContext="{Binding}"/>
</AdornerDecorator>
</TabItem>
</TabControl>

...

我试图在 TabControl 的代码隐藏中重新触发验证 SelectionChanged ,没用。

任何的想法?

最佳答案

拼图

一个 AdornerLayer表示用于渲染装饰器的表面。
作为 AdornerLayer通常服务于整个 View ,而不仅仅是一个控件,一些容器默认实现它们。

一个 adorner是自定义FrameworkElement绑定(bind)到 UIElement .装饰器在 AdornerLayer 中呈现,它是始终位于装饰元素或装饰元素集合之上的渲染表面。

所以在这种情况下,装饰器(红色矩形)绑定(bind)到 TextBox , 但呈现在 TextBox 之上的层中.

通过调用静态方法 GetAdornerLayer 完成修饰(例如,在验证错误的情况下)获取 AdornerLayer UIElement 的对象被装饰。

理论够了

更改 TabItems丢弃 AdornerLayer ,导致装饰器不被绘制。 2个修复:

\手动方式,由 DRapp 提出:

<XAML for MyView1>
<AdornerDecorator>
...
</AdornerDecorator>
</close XAML for MyView1>

当然,如果有另一个容器实现 AdornerLayer AdornerDecorator之间和 TextBox (在视觉树中),这不会有任何好处。所以显式 AdornerDecorator必须是最后一个包装 TextBox .
<XAML for MyView1>
<Grid>

...

<GroupBox>
<AdornerDecorator>
<Grid>

...

<TextBox ... />
</Grid>
</AdornerDecorator>
</GroupBox>
</Grid>
</close XAML for MyView1>

\第二种解决方案(我更喜欢)重置 ErrorTemplate每次 TextBox变得可见。这样做缺少 AdornerLayer被发现并修复。
<UserControl.Resources>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="IsVisible" Value="true">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<Border BorderBrush="Red" BorderThickness="1">
<AdornedElementPlaceholder/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</UserControl.Resources>

关于带有验证的 WPF 文本框丢失 ErrorTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41169165/

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