WPF中设置Popup控件Style的Background背景色不生效问题咨询
问题根因
你写的代码无效的核心原因是WPF原生的Popup控件本身不承担背景渲染职责,它的默认控件模板中没有使用Background属性的可视化元素,直接给Popup的Background属性赋值不会产生任何视觉效果。
解决方案
方案1:直接为Popup内容添加背景层
无需修改现有Style,在Popup内部的最外层套一个Border,直接设置Border的背景色即可:
<Popup Style="{StaticResource popup}"> <Border Background="Blue" Padding="4"> <!-- 此处放置你的Popup内容 --> <TextBlock Text="Popup内容" Foreground="White"/> </Border> </Popup>
方案2:重写Popup的Style模板统一配置背景
如果希望通过Popup的Style统一管控背景属性,需要修改Style重写控件模板,在模板中添加绑定Background属性的Border:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Style TargetType="Popup" x:Key="popup"> <Setter Property="Background" Value="Blue"/> <!-- 重写控件模板,新增背景渲染层 --> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Popup"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"> <ContentPresenter/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary>
注意事项
你当前的Style配置了x:Key="popup",属于显式样式,使用时需要在Popup控件上显式声明Style="{StaticResource popup}"才会生效;如果需要全局所有Popup都应用该样式,删除x:Key属性即可做成隐式样式自动生效。
内容的提问来源于stack exchange,提问作者user16574704
相关产品推荐
相关产品推荐

