为什么我的按钮不出现在ContentPresenter区域?

时间:2012-04-22 15:34:05

标签: c# .net wpf

<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>

按钮应出现在蓝色和黄色矩形之间。

我做错了什么?

2 个答案:

答案 0 :(得分:3)

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

如果要更改ContentControl中的内容呈现方式,则需要将相关标记放在ContentControl的ContentTemplate中。您在上面提到的ContentControl需要看起来如下所示:

<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>

答案 1 :(得分:-1)

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

    <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"/>

简短:您忘了为第一行定义行。

相关问题