Error Style displayed even if the usercontrol is collapsed/hidden
我有一个用户控件来验证其内容。
我正在使用IDataErrorInfo来验证输入(我必须使用.Net 3.5)。
我正在关注本教程:
http://japikse.blogspot.ch/2009/07/idataerrorinfo-error-templates-and-wpf.html
这意味着我正在使用以下样式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <Style TargetType="{x:Type TextBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="Background" Value="Pink"/> <Setter Property="Foreground" Value="Black"/> </Trigger> </Style.Triggers> <Setter Property="Validation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <DockPanel LastChildFill="True" ToolTip="{Binding ElementName=controlWithError,Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"> <TextBlock DockPanel.Dock="Right" Foreground="Red" FontSize="14pt" Margin="-15,0,0,0" FontWeight="Bold">* </TextBlock> <Border BorderBrush="Red" BorderThickness="1"> <AdornedElementPlaceholder Name="controlWithError" /> </Border> </DockPanel> </ControlTemplate> </Setter.Value> </Setter> |
问题是,在某些情况下,我必须隐藏表单(当未选择任何元素时),但是当我显示的表单没有错误时,然后折叠表单(网格), UserControls中的文本框(由于它们不接受空值,因此是无效的)具有红色边框和星号:
未隐藏时的相同形式:
请注意:
它只是可见的ErrorTemplate的内容,未应用触发器的内容(背景为粉红色,前景为黑色)。
所以我认为这种样式有问题,但是我对WPF样式还不够熟悉,以了解原因。
另一个奇怪的事情:
如果我的文本框具有相同的验证(而不是用户控件中的文本框),则它们将被正确隐藏。
编辑
我发现了一些其他的东西,对我有很大帮助,首先是这个主题:
隐藏控件时隐藏验证装饰
这样,我执行了以下操作:将用户控件的可见性绑定到隐藏的元素可见性,然后在用户控件中,将文本框的可见性绑定到用户控件的可见性,然后(最后)添加一个样式触发器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <Style TargetType="{x:Type TextBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="Background" Value="Pink"/> <Setter Property="Foreground" Value="Black"/> </Trigger> <Trigger Property="Visibility" Value="Visible"> <Setter Property="Validation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <DockPanel LastChildFill="True" ToolTip="{Binding ElementName=controlWithError,Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"> <TextBlock DockPanel.Dock="Right" Foreground="Red" FontSize="14pt" Margin="-15,0,0,0" FontWeight="Bold">*</TextBlock> <Border BorderBrush="Red" BorderThickness="1"> <AdornedElementPlaceholder Name="controlWithError" /> </Border> </DockPanel> </ControlTemplate> </Setter.Value> </Setter> </Trigger> </Style.Triggers> </Style> |
几乎可以用了!唯一剩下的就是一个小红点,它是从无处传来的
有什么想法吗?
我找到了一种解决方法,它可能不是最好的方法(如果您有更好的方法,请告诉我!)。
因此,首先,当我使用用户控件时,我将其可见性绑定到要隐藏的用户控件上:
1 | <userContols:BrowseFileControl Visibility="{Binding ElementName=uxFormGrid, Path=Visibility}"/> |
第二,将IDataErrorInfo方法(
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public string this[string columnName] { get { String result=null; if (Visibility == Visibility.Visible) { if (columnName =="FilePath") { if (String.IsNullOrEmpty(FilePath)) { if (!CanBeEmpty) { result ="Mandatory field"; } } else if (!IsValidFilePath(FilePath)) { result ="Malformed path"; } } } return result; } } |
我希望处理样式,但是我没有找到一种方法来完全消除任何红色标记。