将UserControl的依赖属性值传递给其中的Control

时间:2008-10-07 12:03:53

标签: wpf data-binding user-controls

我有一个UserControl(复合控件),可以显示为以下伪XAML代码:

<UserControl>
  <DockPanel>
    <TextBox />
    <Button />
  </DockPanel>
</UserControl>

我在一堆地方使用这个自定义控件,并使用WPF样式设置其中一些。此样式将UserControl的Background属性设置为颜色。但是这个背景颜色是在UserControl的背景表面上绘制的,但我希望它只在TextBox控件的背景上绘制。这就是我得到的(颜色=红色):

alt text http://img261.imageshack.us/img261/8600/62858047wi3.png

如果我将UserControl的Background属性绑定到我的TextBox控件的background属性,我会得到以下内容:

alt text http://img111.imageshack.us/img111/1637/30765795kw5.png

现在它还绘制了内部TextBox控件的背景,但UserControl的Background颜色仍然存在。有没有办法删除UserControl的背景画?

2 个答案:

答案 0 :(得分:5)

有很多方法可以做到这一点,但我建议在用户控件上公开自己的属性,并绑定到用户控件中的属性。例如:

<UserControl x:Name="_root" ...>
    ...
    <Button Background="{Binding ButtonBackground, ElementName=_root}"/>
</UserControl>

另一种方法是将TextBox的背景颜色明确地设置为某种东西。

答案 1 :(得分:1)

我同意肯特。您可以通过多种方式解决此问题。

但是如何在UserControl中使用Style来设置TextBox的背景呢?是否有任何特殊原因以下内容对您不起作用?

<UserControl
    x:Class="StackOverflowQuestion.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300"
    Width="300"
>
    <UserControl.Resources>
        <Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}">
            <Setter Property="Background" Value="Red"/>
        </Style>
    </UserControl.Resources>
    <DockPanel>
        <TextBox Text="Test" Style="{StaticResource textBoxStyle}"/>
        <Button/>
    </DockPanel>
</UserControl>

如果您真的想要在用户控件上使用属性集并使其影响用户控件的内部,我会按照Kent的建议进行一次修改。我将绑定TextBox的背景,以便用户控件上的用户设置的任何Background Brush将流向(属性值继承)Button。或者,换句话说,TextBox的背景确实是你想要做出的不同。

<UserControl x:Name="_root" ...>
    <TextBox Background="{Binding TextBoxBackground, ElementName=_root}"/>
    <Button/>
</UserControl>
相关问题