XAML样式中是否有元素选择器,如CSS中那样?

问题描述 投票:0回答:1

在CSS中,您可以这样做:

#menu, #nav-bar, #data-grid {
    background: autumn-red;
}

XAML样式是否有相似之处?

css wpf xaml css-selectors wpf-controls
1个回答
0
投票

这是我能想到的最接近的:

假设您的Menu,ToolBar和DataGrid WPF组件都具有一个通用基本类型,该基本类型是Control或从Control继承的,则可以使用特定的x:Key定义单个Style,例如在您容器的资源中,将CommonType设置为该公共组件祖先类型的CommonStyle。

然后您可以使用Style =“ {StaticResource CommonStyle}”从每个实例指向该Style。

注意:某些类型实现(实际上是它们的ControlTemplates)根本不使用在公共祖先类型上定义的属性值。例如,DataGrid不支持Background,Toolbar不使用Foreground,但是所有DataGrid,Menu和ToolBar都使用FontSize。

<Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp1" xmlns:sys="clr-namespace:System;assembly=mscorlib" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Window.Resources> <Style x:Key="CommonStyle" TargetType="Control"> <Setter Property="Background" Value="Yellow"/> <Setter Property="Foreground" Value="Red"/> <Setter Property="FontSize" Value="30"/> </Style> </Window.Resources> <StackPanel> <Menu Style="{StaticResource CommonStyle}"> <MenuItem Header="Test"/> </Menu> <ToolBar Style="{StaticResource CommonStyle}"> <Button Content="Test"/> </ToolBar> <DataGrid Style="{StaticResource CommonStyle}"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding}" Header="Item"/> </DataGrid.Columns> <sys:String>Test</sys:String> </DataGrid> </StackPanel> </Window>

Screenshot

希望对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.