【问题标题】:Styling multiple types of WPF controls为多种类型的 WPF 控件设置样式
【发布时间】:2023-04-05 04:11:01
【问题描述】:

我有一个包含几个(不同)项目的堆栈面板:

<StackPanel ...>
    <TextBlock ... />
    <CheckBox ... />
    <CheckBox ... />
    <Button ... />
</StackPanel>

我想将VerticalAlignment="Center" 应用于 StackPanel 的所有子级而不必将VerticalAlignent="Center"Style=... 应用于每个子级。所以,我想我想定义一个适用于 TextBlock、CheckBoxes 和 Button 的隐式样式。

我尝试在堆栈面板的资源中添加 &lt;Style TargetType="FrameworkElement"&gt;,但(显然)这不起作用,因为 TargetType 创建了一个隐式 x:Key {x:Type FrameworkElement},而 TextBlock 仅自动绑定到带有 x 的样式:{x:Type TextBlock}的密钥。

所以,据我所知,我唯一的选择是:(1)在堆栈面板的资源中为所有三种类型创建三种样式,(2)创建一种样式并将其手动绑定到所有子项,( 3) 手动设置所有孩子的VerticalAlignment 选项。 我想要的是: (4) 创建一个样式并自动 将它绑定到堆栈面板的所有子项。那可能吗?或者有没有其他比(1)-(3)冗余更少的解决方案?

【问题讨论】:

    标签: .net wpf xaml styles


    【解决方案1】:

    亨氏,

    如果我正确理解了您的问题,您似乎有一个 StackPanel 想要包含一组孩子。您希望这些孩子拥有VerticalAlignment="Center" 的样式,但您不想将此属性添加到每个孩子。如果是这种情况,我有一个解决方案:

    但是,无法设置基础对象的属性并将它们用于继承的类。所以,FrameworkElement 有一个属性VerticalAlignment,但您不能直接在样式中设置它并自动应用它。在我提出的解决方案中,您必须为每个对象类型创建一个样式,但您不必为每个对象创建一个不同的样式。在我的解决方案中,您可以创建一个“BaseStyle”,然后将您的其他每个样式都基于这个样式以获得所需的结果。所以你可以这样做:

    <Window x:Class="Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="500">
        <Window.Resources>
            <ResourceDictionary>
                <Style x:Key="BaseStyle" TargetType="{x:Type FrameworkElement}">
                    <Style.Setters>
                        <Setter Property="VerticalAlignment" Value="Center" />
                    </Style.Setters>
                </Style>
    
                <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource BaseStyle}" />
                <Style TargetType="{x:Type CheckBox}" BasedOn="{StaticResource BaseStyle}" />
                <Style TargetType="{x:Type Button}" BasedOn="{StaticResource BaseStyle}" />
            </ResourceDictionary>
        </Window.Resources>
        <Grid>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="testing textblock" />
                <CheckBox  Content="testing check1 "/>
                <CheckBox Content="testing check2" />
                <Button Content="testing button" />
            </StackPanel>
        </Grid>
    </Window>
    

    此外,您可以通过Application.xaml 在应用程序级别设置这些。这意味着您只需创建一次这些样式,并且您不需要在所有页面/屏幕上实现它们。

    希望对你有帮助,

    谢谢!

    【讨论】:

    • 感谢您的回答。这并不像我希望的那么简单(例如
    猜你喜欢
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 2010-11-13
    相关资源
    最近更新 更多