首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

WPF,模板的属性设置有关问题

2013-07-08 
WPF,模板的属性设置问题下面这个Button模板,来自MSDN的例子 Window.ResourcesStyle TargetTypeButton

WPF,模板的属性设置问题
下面这个Button模板,来自MSDN的例子


 <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border Name="RootElement">
                            <Border.Background>
                                <SolidColorBrush x:Name="BorderBrush" Color="Black"/>
                            </Border.Background>
                            <Grid Margin="4" Background="{TemplateBinding Background}">
                                <ContentPresenter
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                    Margin="4,5,4,4" />
                            </Grid>
                        </Border>


                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid Height="100" Name="grid1" Width="200">
        <Button Content="Button" Height="31" Foreground="Red" HorizontalAlignment="Left" Margin="60,45,0,0" Name="button1" VerticalAlignment="Top" Width="78" />
    </Grid>




我想问的是:
模板中的ContentPresenter,并没有绑定Foreground属性,为什么设置Button的Foreground属性,能起到作用呢?没有绑定的话,应该继承父元素的属性的啊
[解决办法]
父元素是Grid,父元素的父元素不就是Button嘛。
[解决办法]
你直接设置<Button Content="Button" Height="31" Foreground="Red> 这样肯定会有颜色啦。当模版没有绑定改变的时候,不代表你在button上不能改变Foreground颜色啊。
[解决办法]
有人知道么......
[解决办法]
你要知道ContentPresenter的作用,它就相当于一个默认自动绑定使用模板的元素的Content内容的ContentControl,而你Button的Content相当于一个TextBlock,设置字体大小,颜色都会影响到的。
[解决办法]
ContentPresenter内部做了默认的绑定.

http://www.cnblogs.com/Clingingboy/archive/2010/12/20/1911388.html
[解决办法]
引用:
Quote: 引用:

你要知道ContentPresenter的作用,它就相当于一个默认自动绑定使用模板的元素的Content内容的ContentControl,而你Button的Content相当于一个TextBlock,设置字体大小,颜色都会影响到的。

照你这么说,如果代码中没有绑定Background属性的句子,在Button上设置Background也会起作用的洛? 

不会,Button的默认Content只是个文字而已,会影响的也就字体跟字体颜色。其他比如长宽,背景都是通过模板绑定来实现的。
如果你改变了Button的Content,那么才可能受影响。
比如

        <Button Width="100" Height="30" Background="Gray" Foreground="Red">


            <Grid Width="{Binding Width,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Button}}}" Background="{Binding Background,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Button}}}" Height="{Binding Height,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Button}}}">
                <TextBlock Text="test"/>
            </Grid>
        </Button>


这个的Content跟父元素的背景绑定了。这样模板没绑定背景的情况下,只用ContentPresenter也会跟着设置的背景变化。

热点排行