如何为Label和TextBox创建通用XAML样式以避免重复?
如何为Label和TextBox创建通用XAML样式
当然可以实现这种通用样式,不用重复编写代码!核心思路是找到Label和TextBox的共同基类——FrameworkElement,把样式的TargetType设置为它就可以了。
具体实现步骤
因为Margin是FrameworkElement的公共属性,而Label和TextBox都是这个基类的派生控件,所以这个样式能同时应用在两者身上。完整代码如下:
<!-- 定义通用静态资源样式 --> <Style x:Key="Style1" TargetType="{x:Type FrameworkElement}"> <Setter Property="Margin" Value="0,0,20,0" /> <!-- 你还可以添加更多两者共有的属性,比如字体、内边距等 --> <Setter Property="FontSize" Value="14" /> <Setter Property="Padding" Value="5" /> </Style> <!-- 在控件上应用样式 --> <Label Style="{StaticResource Style1}" Text="示例标签" /> <TextBox Style="{StaticResource Style1}" PlaceholderText="示例输入框" />
注意事项
- 只能在这个通用样式里设置基类
FrameworkElement(或更高层级基类)的公共属性,如果尝试设置Label或TextBox的特有属性(比如Label的ContentStringFormat、TextBox的AcceptsReturn),运行时会抛出异常,因为另一个控件没有这个属性。 - 如果需要给某个控件单独扩展样式,可以用
BasedOn继承通用样式,避免重复写公共属性:
<!-- 基于通用样式扩展TextBox专属样式 --> <Style x:Key="CustomTextBoxStyle" TargetType="{x:Type TextBox}" BasedOn="{StaticResource Style1}"> <Setter Property="AcceptsReturn" Value="True" /> <Setter Property="BorderBrush" Value="#ccc" /> </Style>
内容的提问来源于stack exchange,提问作者Pierre
相关产品推荐
相关产品推荐

