WPF资源部分不影响视图中的Label控件



我已经创建了一个"必填字段"标签的样式,它应该在标签前面放置一个红色星号"*"。这是我从应用程序中获取的示例。我的WPF应用程序的资源部分:

    <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:"/>

令人恼火的是,它似乎没有修改标签。有人能告诉我我做错了什么吗?

你的风格似乎不对。我也会那样做。

<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>

这个应该可以,但是它完全没有经过测试。

模板被分配给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}">

最新更新