【问题标题】:Style defined in a resource section for all controls in a window在资源部分中为窗口中的所有控件定义的样式
【发布时间】:2013-01-07 01:23:25
【问题描述】:

当我们在 XAML 资源部分中定义 Style 并将其 TargetType 属性设置为特定控件类型时,我们不需要将 Style 属性设置为该类型的控件。例如

<Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Content" Value="Style set for all buttons"/>
            <Setter Property="Background" Value="Gray"/>
        </Style>
    </Window.Resources>
    <Grid>
        <Button Height="27" HorizontalAlignment="Left" Margin="119,56,0,0" Name="button1" VerticalAlignment="Top" Width="140" />
        <Button Style="{x:Null}" Content="No Style" Height="27" HorizontalAlignment="Left" Margin="212,121,0,0" Name="button2" VerticalAlignment="Top" Width="141" />
        <Button  Content="Button" Height="25" HorizontalAlignment="Left" Margin="296,183,0,0" Name="button3" VerticalAlignment="Top" Width="158" />
    </Grid>

但是当我们想为窗口中的所有控件定义样式时,我们需要为每个控件添加 Style 属性以具有该定义的样式。例如

<Window.Resources>
        <Style x:Key="Style1" TargetType="Control">
            <Setter Property="Control.Background" Value="Gray"/>
        </Style>
    </Window.Resources>
    <Grid>
        <Button Style="{StaticResource Style1}" Content="Button" Height="23" HorizontalAlignment="Left" Margin="67,52,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
        <Label Style="{StaticResource Style1}" Content="Label" Height="27" HorizontalAlignment="Left" Margin="189,99,0,0" Name="label1" VerticalAlignment="Top" Width="83" />
    </Grid>

如果不专门在按钮和标签控件中设置样式属性,我们不能在上面的示例中使用按钮和标签访问样式“Style1”吗?

提前致谢。

【问题讨论】:

    标签: wpf


    【解决方案1】:

    关于here的类似问题

    普遍的共识是,您不能将样式应用于像控件这样深奥的东西。考虑到广泛的属性和控件,我可以理解为什么系统拒绝/忽略它。我建议也许这样的事情可以让你非常接近你想要的:

    <Style x:Key="general" TargetType="{x:Type Control}">
            <Setter Property="Control.Background" Value="Green"/>
    </Style>
    <Style BasedOn="{StaticResource general}" TargetType="{x:Type Button}"/>
    <Style BasedOn="{StaticResource general}" TargetType="{x:Type Label}"/>
    <Style BasedOn="{StaticResource general}" TargetType="{x:Type CheckBox}"/>
    

    【讨论】:

    • 谢谢,它得出的结论是,我们不能通过仅定义一种针对“控件”类的样式来为所有控件提供通用样式。我们可以通过单独继承该样式来将该样式用于其他控件。
    【解决方案2】:

    尝试&lt;Style TargetType="Button" BasedOn="{StaticResource style1}"/&gt; 用于按钮,其他用于标签等等...

    【讨论】:

    • 谢谢,我明白一个单一的风格定位'控件'类不能直接应用于其他控件,如按钮、标签等。我们需要从基本样式继承它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    相关资源
    最近更新 更多