【问题标题】:Setting a style on Control type not working在控件类型上设置样式不起作用
【发布时间】:2010-11-13 21:29:30
【问题描述】:

我正在编写一个非常基本的 WPF 对话框,并希望将简单的样式应用于从 Control 类继承的所有对象。我正在使用的代码:

<Window.Resources>
    <Style TargetType="{x:Type Control}">
        <Setter Property="Margin" Value="20"/>
    </Style>
</Window.Resources>
 <StackPanel>
    <TextBlock Text="some text"/>
    <TextBox x:Name="x_NameTextBox"/>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
        <Button x:Name="x_CancelButton" Click="x_CancelButton_Click" Content="Cancel"/>
        <Button x:Name="x_OkButton" Click="x_OkButton_Click" Content="OK"/>
    </StackPanel>
</StackPanel>
</Window>

上面定义的样式根本不会改变窗口的布局,除非我指定一个键并为每个单独的对象设置样式,这正是我想要避免的。它也适用于更具体的类型(例如,将 TargetType 设置为 Button。)

任何想法为什么这不起作用?

【问题讨论】:

标签: c# .net wpf xaml styles


【解决方案1】:

每个控件在实例化时都会从显式定义的资源中获取其样式,或者查找可以获取默认样式的直接父级。在您的情况下,Button 控件将从平台获取其默认样式,因为您的 App 尚未定义。现在,平台按钮样式无法了解您自定义的 Control 基本样式。因为只有当您明确定义 BasedOn

时,样式才会查找基本样式

所以你只有两种方法 1.为每个控件定义样式-我认为您不希望这样做。 2.为你感兴趣的控件定义Styles并设置BasedOn

<Style TargetType="{x:Type Control}">
    <Setter Property="Margin" Value="20"/>
</Style>

<Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Control}}">
</Style>  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2023-04-05
    • 2017-06-25
    • 1970-01-01
    • 2020-03-08
    • 2014-09-02
    相关资源
    最近更新 更多