0

我通过从 ContentControl 继承来创建自定义控件。下面是 Generic.xaml 中的 XAML 代码

<Style TargetType="local:MyCustomControl">
    <Setter Property="Background" Value="YellowGreen"></Setter>
    <Setter Property="IconSource" Value="/Themes/icon.png"></Setter>

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyCustomControl">
                <Border BorderBrush="White" BorderThickness="2">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="100"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Image Grid.Column="0" Source="{TemplateBinding IconSource}" Stretch="None"></Image>

                        <Border Background="{TemplateBinding Background}"  Grid.Column="1">
                            <ContentPresenter x:Name="ContentContainer" 
                                              Content="{TemplateBinding Content}" 
                                              ContentTemplate="{TemplateBinding ContentTemplate}" 
                                              Margin="{TemplateBinding Padding}">
                            </ContentPresenter>
                        </Border>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>

    </Setter>
</Style>

在我的应用程序中,我以这种方式使用了自定义控件:

    <mycontrol:MyCustomControl Height="100" Width="400" 
                               Foreground="Red"
                               IconSource="/Assets/ApplicationIcon.png">
        <mycontrol:MyCustomControl.Content>
            <StackPanel>
                <TextBlock  Text="Some Text Content Here"/>
                <Button Content="Test Button" Foreground="Pink" Background="Black"/>
            </StackPanel>
        </mycontrol:MyCustomControl.Content>
    </mycontrol:MyCustomControl>

我不明白stackpanel 中的文本块文本如何以及为什么会变成红色。有人可以用简单的话解释我如何以及为什么会发生这种情况吗?

这是输出:

在此处输入图像描述

4

1 回答 1

0

那是因为

<mycontrol:MyCustomControl Height="100" Width="400" 
                           Foreground="Red"
                           IconSource="/Assets/ApplicationIcon.png">

Foreground然后沿元素树继承到您的StackPanel,TextBlockButton中,但是因为ButtonForeground明确设置它不是红色的。

于 2013-04-13T07:02:34.353 回答