如何通过Xamarin.Forms样式设置所有ImageButton的FontImageSource.Color属性?
方法1:使用FontImageSource的隐式样式
直接定义目标类型为FontImageSource的隐式样式,所有作为ImageButton Source的FontImageSource实例都会自动应用该样式:
<ResourceDictionary> <!-- 全局生效的FontImageSource隐式样式 --> <Style TargetType="FontImageSource"> <Setter Property="Color" Value="#FF4081" /> <!-- 替换为你需要的颜色值 --> </Style> </ResourceDictionary>
后续使用ImageButton时,只要Source是FontImageSource类型,Color属性就会自动继承样式配置:
<ImageButton> <ImageButton.Source> <FontImageSource Glyph="" FontFamily="MaterialIcons" /> </ImageButton.Source> </ImageButton>
方法2:在ImageButton样式中绑定控制(限Source已确定为FontImageSource的场景)
如果需要在ImageButton的专属样式中直接控制,可通过绑定自身Source属性并转换类型来设置Color:
<Style TargetType="ImageButton"> <!-- 其他ImageButton属性设置 --> <Setter Property="Padding" Value="8" /> <!-- 绑定Source的Color属性,需确保Source是FontImageSource实例 --> <Setter Property="(FontImageSource.Color)" Value="{Binding Source={RelativeSource Self}, Path=Source.Color, TargetNullValue=Blue}" /> </Style>
这种方式依赖于ImageButton的Source已明确为FontImageSource,否则会失效,通用性不如方法1。
关键注意点
- 若FontImageSource实例自身显式设置了Color属性,会优先覆盖样式中的配置,需移除这类局部设置。
- 把样式放在
App.xaml的ResourceDictionary中可实现全局生效,放在页面级资源中则仅作用于当前页面。
内容的提问来源于stack exchange,提问作者Victor Gray
相关产品推荐
相关产品推荐

