日期:2014-05-17  浏览次数:20861 次

WPF,这是附加属性还是属性值继承

 <Grid TextBlock.Foreground="White" TextBlock.FontSize="30">
     <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="125,146,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
     <TextBlock Height="23" HorizontalAlignment="Left" Margin="256,207,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" />
   </Grid>


在Grid的TextBlock.Foreground="White",写成Button.Foreground为什么会报错:
未在类型“Button”中找到可附加的属性“Foreground”。

难道说TextBlock.Foreground是附加属性吗?到底是附加属性还是属性值继承呢?

------解决方案--------------------
就是按钮没有Foreground属性。

就好像猴子有尾巴,人没有尾巴一样。。。
------解决方案--------------------
其实怎么说不重要,关键是它做了什么比较重要。


------解决方案--------------------
所谓附加属性只是语法糖,它不是属性,而是方法。在TextBlock类型,代码是这样的
        public static void SetForeground(DependencyObject element, Brush value)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            element.SetValue(TextBlock.ForegroundProperty, value);
        }

------解决方案--------------------
很显然,如果编译器在Button类中找不到叫做 SetForeground 的公共静态方法,它就会报告你说:找不到 Foreground 这个附加属性。
------解决方案--------------------
可能一开始不习惯,但是有经验的人应该在12个小时内就充分明白其作用。这种语法糖非常有用。我们希望让交互界面设计师、尽量不写代码、尽量使用Blend等等美工板绘图工具来开发程序,因此我们需要在xaml的风格上直接调用各种各样过去只有程序员才能调用的代码。现在许多代码都是被声明方式——作为属性——而调用的,包括大量的SetXXXXX、GetXXXXX公共方法,包括事件、包括行为和动画等等,都是不需要写一行代码就可以轻松调用的。