ControlTemplate不显示网格

时间:2012-05-22 22:47:02

标签: c# wpf xaml controltemplate

我正在尝试创建一个包含网格的Button,其中的行包含某些文字。

Button将有两行,两行都有不同的文字。显示传递给ControlTemplate的文本,但不显示模板中指定的文本。

此外,Grid行的高度未显示。我希望它扩展按钮的高度。事实上,我不确定网格是否真的显示出来。

<Window x:Class="MAQButtonTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="695" Width="996">        
    <Window.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="OverridesDefaultStyle" Value="True"/>
        </Style>
        <ControlTemplate TargetType="Control" x:Key="1">
            <Grid Width="444">
                <Grid.RowDefinitions>
                    <RowDefinition Height="51" />
                    <RowDefinition Height="36" />
                </Grid.RowDefinitions>
                <Grid Grid.Row="0" Background="#286c97">
                    <TextBlock>This is the first piece of text</TextBlock>
                </Grid>
                <Grid Grid.Row="1" Background="#5898c0">
                    <ContentPresenter Grid.Row="0" />
                </Grid>
            </Grid>
        </ControlTemplate>
    </Window.Resources>
    <Grid>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="300" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid Grid.Column="0" Background="#e9f1f6"></Grid>
        <Grid Grid.Column="1" Background="#d2e3ed">
            <StackPanel>
                <TextBlock FontFamily="Segoe UI" FontSize="22" FontWeight="Medium" Margin="52,58,0,0" Foreground="#0c3d5d">Your Quizzes <TextBlock FontFamily="Segoe UI" FontSize="18" FontWeight="Medium" Foreground="#0c3d5d">(7)</TextBlock></TextBlock>
                <Grid>
                    <Button Width="444" Background="{x:Null}" BorderThickness="0" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}">
                        <TextBlock>This is a second piece of text</TextBlock>
                    </Button>
                </Grid>
            </StackPanel>
        </Grid>

    </Grid>
</Window>

以下是它如何通过粗略说明我想要实现的按钮布局:

Current vs What I want

2 个答案:

答案 0 :(得分:3)

当您设置模板

时,您正在设置按钮的样式

资源:

    <ControlTemplate TargetType="Button" x:Key="ButtonTemplate">
        <Grid Width="444">
            <Grid.RowDefinitions>
                <RowDefinition Height="51" />
                <RowDefinition Height="36" />
            </Grid.RowDefinitions>
            <Grid Grid.Row="0" Background="#286c97">
                <TextBlock>This is the first piece of text</TextBlock>
            </Grid>
            <Grid Grid.Row="1" Background="#5898c0">
                <ContentPresenter />
            </Grid>
        </Grid>
    </ControlTemplate>

按钮:

    <Button Template="{StaticResource ButtonTemplate}" >
        Text 2
    </Button>

答案 1 :(得分:0)

为什么使用TargetType作为“Control”,请使用Button。您需要定义一个按钮。使用“混合”编辑按钮模板以从中删除所有不必要的内容。