在HTML/CSS中,您可以定义可应用于许多类型元素的样式,例如:
.highlight {
color:red;
}
Run Code Online (Sandbox Code Playgroud)
可以应用于P和DIV,例如:
<p class="highlight">this will be highlighted</p>
<div class="highlight">this will also be highlighted</div>
Run Code Online (Sandbox Code Playgroud)
但在XAML中,您似乎必须为样式定义TargetType,否则会出现错误:
<Style x:Key="formRowLabel" TargetType="TextBlock">
Run Code Online (Sandbox Code Playgroud)
有没有办法允许XAML样式应用于多个元素,甚至像CSS一样让它保持打开状态?
Jos*_*h G 69
在编译期间检查WPF样式中的setter; CSS样式是动态应用的.
您必须指定一个类型,以便WPF可以将setter中的属性解析为该类型的依赖项属性.
您可以将目标类型设置为包含所需属性的基类,然后将该样式应用于派生类.例如,您可以为Control对象创建样式,然后将其应用于多种类型的控件(Button,TextBox,CheckBox等)
<Style x:Key="Highlight" TargetType="{x:Type Control}">
<Setter Property="Foreground" Value="Red"/>
</Style>
Run Code Online (Sandbox Code Playgroud)
...
<Button Style="{StaticResource Highlight}" Content="Test"/>
<TextBox Style="{StaticResource Highlight}" Text="Test"/>
<CheckBox Style="{StaticResource Highlight}" Content="Test"/>
Run Code Online (Sandbox Code Playgroud)
小智 37
<!-- Header text style -->
<Style x:Key="headerTextStyle">
<Setter Property="Label.VerticalAlignment" Value="Center"></Setter>
<Setter Property="Label.FontFamily" Value="Trebuchet MS"></Setter>
<Setter Property="Label.FontWeight" Value="Bold"></Setter>
<Setter Property="Label.FontSize" Value="18"></Setter>
<Setter Property="Label.Foreground" Value="#0066cc"></Setter>
</Style>
<!-- Label style -->
<Style x:Key="labelStyle" TargetType="{x:Type Label}">
<Setter Property="VerticalAlignment" Value="Top" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Margin" Value="0,0,0,5" />
</Style>
Run Code Online (Sandbox Code Playgroud)
我认为这两种声明样式的方法都可以回答你的问题.在第一个中,没有指定TargetType,但属性名称以"Label"为前缀.在第二个中,为Label对象创建样式.
另一种方法是:
<UserControl.Resources>
<Style x:Key="commonStyle" TargetType="Control">
<Setter Property="FontSize" Value="24"/>
</Style>
<Style BasedOn="{StaticResource commonStyle}" TargetType="ListBox"/>
<Style BasedOn="{StaticResource commonStyle}" TargetType="ComboBox"/>
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)
我想将样式应用于 Textblock 和 TextBox,但所选答案对我不起作用,因为 Textblock 不继承自 Control,在我的情况下,我想影响 Visibility 属性,所以我使用了FrameworkElement
<Style x:Key="ShowIfRequiredStyle" TargetType="{x:Type FrameworkElement}">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ShowIfRequiredStyle, UpdateSourceTrigger=PropertyChanged}" Value="true">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
<TextBlock Style="{StaticResource ResourceKey=ShowIfRequiredStyle}"/>
<TextBox Style="{StaticResource ResourceKey=ShowIfRequiredStyle}"/>
Run Code Online (Sandbox Code Playgroud)
这适用于 Visibility 属性,因为这两个项都从 Frameworkelement 继承,并且属性是在那里定义的。当然,这不适用于仅在 Control 中定义的属性,您可以搜索层次结构树并尝试查找基类,无论如何我认为这可以帮助某人,因为这是一个顶级搜索结果并且所选答案有点不完整。
归档时间: |
|
查看次数: |
46773 次 |
最近记录: |