您能否为一种 XAML 样式定义多个 TargetType? [英] Can you define multiple TargetTypes for one XAML style?

查看:33
本文介绍了您能否为一种 XAML 样式定义多个 TargetType?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 HTML/CSS 中,您可以定义可应用于多种类型元素的样式,例如:

In HTML/CSS you can define a style which can be applied to many types of elements, e.g.:

.highlight {
    color:red;
}

可以同时应用于 P 和 DIV,例如:

can be applied to both P and DIV, e.g.:

<p class="highlight">this will be highlighted</p>
<div class="highlight">this will also be highlighted</div>

但在 XAML 中,您似乎必须为样式定义 TargetType,否则会出现错误:

but in XAML you seem to have to define the TargetType for styles, otherwise you get an error:

<Style x:Key="formRowLabel" TargetType="TextBlock">

有没有办法允许 XAML 样式应用于多个元素,甚至像在 CSS 中一样保持打开状态?

is there a way to allow a XAML style to be applied to multiple elements or even to leave it open as in CSS?

推荐答案

WPF 样式中的 setter 在编译时检查;CSS 样式是动态应用的.

The setters in WPF styles are checked during compile time; CSS styles are applied dynamically.

您必须指定一个类型,以便 WPF 可以将 setter 中的属性解析为该类型的依赖属性.

You have to specify a type so that WPF can resolve the properties in the setters to the dependency properties of that type.

您可以将目标类型设置为包含所需属性的基类,然后将该样式应用于派生类.例如,您可以为 Control 对象创建一个样式,然后将其应用于多种类型的控件(按钮、文本框、复选框等)

You can set the target type to base classes that contain the properties you want and then apply that style to derived classes. For example, you could create a style for Control objects and then apply it to multiple types of controls (Button, TextBox, CheckBox, etc)

<Style x:Key="Highlight" TargetType="{x:Type Control}">
    <Setter Property="Foreground" Value="Red"/>
</Style>

...

<Button Style="{StaticResource Highlight}" Content="Test"/>
<TextBox Style="{StaticResource Highlight}" Text="Test"/>
<CheckBox Style="{StaticResource Highlight}" Content="Test"/>

这篇关于您能否为一种 XAML 样式定义多个 TargetType?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆