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

WPF,请看下这个UserControl

<UserControl x:Class="WPF1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Button Height="30" Width="50" Background="{Binding Foreground, ElementName=this}"/>
    </Grid>
</UserControl>



<Window x:Class="WPF1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WPF1"
        Title="MainWindow" Height="450" Width="925" Background="#FFEFDB96">
    <Grid>
        <local:UserControl1 HorizontalAlignment="Left" Foreground="Red" Height="142" Margin="202,132,0,0" VerticalAlignment="Top" Width="234"/>
    </Grid>
</Window>


UserControl中,有一个Button,其Background绑定到控件的Foreground属性上,使用的时候,设置了Foreground为红色,可是Button为什么没有呈现红色呢?

------解决方案--------------------
UserControl-->Grid-->Button
你设置的是UserControl的Foreground属性,而不是Button的Foreground属性,看清楚可视化树的结构。
------解决方案--------------------
ElementName=this
可能我水平不够,WPF搞了这个长时间没见过这种用法
------解决方案--------------------
2楼正解
------解决方案--------------------
Element不要
UC里面加

<UserControl   

....
DataContext="{Binding RelativeSource={RelativeSource Self}}"/>
------解决方案--------------------
Background="{Binding Foreground}
------解决方案--------------------
参考 附加属性的定义使用

//先看这个
http://silverlightchina.net/html/tips/2011/0520/7769.html

//这是附加属性依赖属性的定义
http://www.cnblogs.com/024hi/archive/2010/02/02/Unleash_DependencyProperty_In_Silverlight.html