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

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 Background="Red">
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
    </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" Height="350" Width="600" Name="ddd">
    <Grid>
        <local:UserControl1 HorizontalAlignment="Left" Content="张三" Height="100" Margin="119,77,0,0" VerticalAlignment="Top" Width="100"/>
    </Grid>
</Window>


有两个问题请教:
1:自定义的UserControl中,将Grid的Background属性设置为红色,但是使用控件的时候,为什么不是红色呢?
2:在使用控件的时候,如果将UserControl的Background属性设置为红色,为什么就变成红色的了呢?在UserControl中,并没有将Grid的Background属性绑定到控件的Background属性上啊?

------解决方案--------------------
UserControl自身也有Background属性,也是可以生效的
你的问题,应该是这样的

<m:UserControl1 Width="100" Height="100" Background="Blue" >
            <Grid>
            </Grid>
        </m:UserControl1>

你的控件的Content很有可能被你重新赋值了,如上述代码所示
当你的Content没有赋值时,UserControl加载的是默认的UserControl设计时的内容,而如果你像上面一样,对其Content进行了类似与重赋值的操作,就像你上面的代码一样:
UserControl的内容不再是:

<Grid Background="Red">
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
    </Grid>

而是变成了:
“张三”
所以Grid不存在了,那里还来的颜色
------解决方案--------------------
引用:
Quote: 引用:

ContentPresenter