我为“必填字段”标签创建了一个样式,该标签应在标签前面放置一个红色的星号“*”。这是我从我的WPF应用程序的Application.Resources部分获取的xaml:
<Style TargetType="Label" x:Key="RequiredField">
<Setter Property="Margin" Value="0,0,5,0" />
<Setter Property="HorizontalAlignment" Value="Right" />
<Setter Property="Content">
<Setter.Value>
<ControlTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="*" Foreground="Red" FontSize="10"/>
<TextBlock Text="{Binding}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我视图中的xaml使用如下资源:
<Label Grid.Row="1" Grid.Column="0" Style="{StaticResource RequiredField}" Content="Name:"/>
令人讨厌的是它似乎没有修改标签。谁能告诉我我做错了什么?
答案 0 :(得分:1)
你的风格似乎错了。我会这样试试。
<Style TargetType="Label" x:Key="RequiredField">
<Setter Property="Margin" Value="0,0,5,0" />
<Setter Property="HorizontalAlignment" Value="Right" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Label}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="*" Foreground="Red" FontSize="10"/>
<TextBlock Text="{TemplateBinding Content}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
这应该可以解决问题,但它完全没有经过测试。
答案 1 :(得分:0)
模板已分配给Content属性。那是错的。
相反,它可以分配给Template属性,但在这种情况下,最好使用Validation.ErrorTemplate属性,因为它适用于验证装饰器。
<ControlTemplate x:Key="TextBoxErrorTemplate">
<StackPanel>
<StackPanel Orientation="Horizontal">
<Image Height="16" Margin="0,0,5,0"
Source="Assets/warning_48.png"/>
<AdornedElementPlaceholder x:Name="Holder"/>
</StackPanel>
<Label Foreground="Red" Content="{Binding ElementName=Holder,
Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
</StackPanel>
</ControlTemplate>
<TextBox x:Name="Box"
Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}">