c# - ContentControl 不显示内容

标签 c# wpf xaml binding contentcontrol

我有一个自定义 ContentControl,它具有固定的 XAML 布局,如 UserControl(而不是通常应用的通用模板)。

以前这个布局没有额外的标记,所以它的字面意思是:

<ContentControl x:Class="MyControls.CustomViewControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
</ContentControl>

这很好用。

我现在想在内容周围放置一个边框,所以我将 XAML 更改为:

<ContentControl x:Class="MyControls.CustomViewControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <ContentControl.Template>
        <ControlTemplate>
            <Border BorderThickness="5" BorderBrush="LightGreen">
                <ContentPresenter />
            </Border>
        </ControlTemplate>
    </ContentControl.Template>
</ContentControl>

这显示了边框,但没有内容。

我尝试为 ContentPresenter 提供显式绑定(bind):

<ContentPresenter Content="{Binding Path=Content, RelativeSource={RelativeSource Self}}"/>

但这并没有什么不同。

设置显式 Content 确实有效:

<ContentPresenter Content="TEST" />

有人知道为什么内容绑定(bind)不起作用吗?我想我可以回退到通常的通用模板,但如果我可以像 UserControl 一样直接这样做会更容易。

最佳答案

为控件模板添加 TargetType

<ContentControl.Template>
    <ControlTemplate  TargetType="Button">
        <Border BorderThickness="5" BorderBrush="LightGreen">
            <ContentPresenter />
        </Border>
    </ControlTemplate>
</ContentControl.Template>

关于c# - ContentControl 不显示内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12705907/

相关文章:

WPF:带按钮的动态菜单

c# - 在 Metro 风格应用程序中将图像下载到本地存储

c# - 基于 C# 中搜索文本框的文本将 ListView CollectionViewSource 滚动到一组项目

c# - 使用 ItemSource 绑定(bind)访问 ListView 内的另一个数据上下文

c# - 获取回发触发器

时间:2019-03-17 标签:c#SHA-256Hash

c# - DesignerAttribute 用法

c# - 并行数据处理

c# - 为什么我的图片从上到下逐行更新

c# - 在行为中使用静态资源