为什么我的按钮没有出现在内容演示器区域中

本文关键字:区域 按钮 我的 为什么 | 更新日期: 2023-09-27 18:31:58

<ContentControl x:Class="Test.MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Width="200" Height="200" >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Rectangle Fill="Blue"/>
        <ContentPresenter Grid.Row="1" Content="{TemplateBinding ContentControl.Content}" />
        <Rectangle Fill="Yellow" Grid.Row="2"/>
    </Grid>
</ContentControl>
<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Test="clr-namespace:Test" Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Test:MyControl2>
            <Button/>
        </Test:MyControl2>
    </Grid>
</Window>

按钮应显示在蓝色和黄色矩形之间。

我做错了什么?

为什么我的按钮没有出现在内容演示器区域中

问题是您要定义两次 ContentControl 的内容:一次在 ContentControl 中,一次在 Window.xaml 中。 Window.xaml中的内容将覆盖 ContentControl 中的内容,因此您会看到一个按钮,其上方和下方没有彩色矩形。

如果要更改 ContentControl 中

内容的呈现方式,则需要将相关标记放在 ContentControl 的ContentTemplate中。 上面介绍的内容控件需要如下所示:

<ContentControl x:Class="Test.MyControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         Width="200" Height="200" >
    <ContentControl.ContentTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Rectangle Fill="Blue"/>
                <ContentPresenter Grid.Row="1" Content="{TemplateBinding ContentControl.Content}" />
                <Rectangle Fill="Yellow" Grid.Row="2"/>
            </Grid>
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

我不是专业人士,但我会更改这些行:

    <Rectangle Fill="Blue"/>
    <ContentPresenter Grid.Row="1" Content="{TemplateBinding ContentControl.Content}" />
    <Rectangle Fill="Yellow" Grid.Row="2"/>

对此:

    <Rectangle Fill="Blue" Grid.Row="0"/>
    <ContentPresenter Grid.Row="1" Content="{TemplateBinding ContentControl.Content}" />
    <Rectangle Fill="Yellow" Grid.Row="2"/>

简短:您忘记定义第一个行。