为WPF中的ContentControl设置背景色

本文背景:在使用Prism框架的WPF中,直接为ContentControl设置Background不起作用。

参考资料:ContentControl in ControlTemplate does not show Border nor Background

1、问题原因

ContentControl默认的Style不包含渲染Border和Background属性的方法,它仅仅含有一个ContentPresenter对象。

2、解决方法

为了给ContentControl添加背景色,需要为其添加包含所需元素的自定义模板,如下所示:

复制代码
<ContentControl regions:RegionManager.RegionName="ContentRegion" Margin="{Binding ContentMargin}"
                HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <ContentControl.Template>
        <ControlTemplate TargetType="ContentControl">
            <Border Background="{Binding ContentBrush}">
                <ContentPresenter Content="{TemplateBinding Content}"
                                  ContentTemplate="{TemplateBinding ContentTemplate}"
                                  Cursor="{TemplateBinding Cursor}"
                                  HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
            </Border>
        </ControlTemplate>
    </ContentControl.Template>
</ContentControl>
复制代码

3、问题总结

在上述代码中,为ContentControl的模板添加了Border,并为Border设置了Background,然后在Border中再添加ContentPresenter对象,这样便使得ContentPresenter渲染的控件能够具有指定的背景了,前面的问题得到解决。

posted @   xhubobo  阅读(775)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
点击右上角即可分享
微信分享提示