为WPF中的ContentControl设置背景色
本文背景:在使用Prism框架的WPF中,直接为ContentControl设置Background不起作用。
参考资料:ContentControl in ControlTemplate does not show Border nor Background。
1、问题原因
ContentControl默认的Style不包含渲染Border和Background属性的方法,它仅仅含有一个ContentPresenter对象。
2、解决方法
为了给ContentControl添加背景色,需要为其添加包含所需元素的自定义模板,如下所示:
"ContentRegion" Margin="{Binding ContentMargin}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> "ContentControl"> "{Binding ContentBrush}"> "{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" Cursor="{TemplateBinding Cursor}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
3、问题总结
在上述代码中,为ContentControl的模板添加了Border,并为Border设置了Background,然后在Border中再添加ContentPresenter对象,这样便使得ContentPresenter渲染的控件能够具有指定的背景了,前面的问题得到解决。