转移依赖项属性值到内部的控制它
问题描述:
我有个用户控件(复合控制),其可以表示为下面的伪XAML代码:转移依赖项属性值到内部的控制它
<UserControl>
<DockPanel>
<TextBox />
<Button />
</DockPanel>
</UserControl>
我在一堆使用该自定义控制使用WPF Style放置和设置其中的一些。此样式将UserControl的Background属性设置为一种颜色。但是这种背景颜色是在UserControl的背景表面上绘制的,但我希望它仅在TextBox控件的背景上绘制。这是我所得到的(颜色为红色):
alt text http://img261.imageshack.us/img261/8600/62858047wi3.png
如果我的用户控件的背景属性绑定到我的TextBox控件的背景属性,我得到以下之一:
alt text http://img111.imageshack.us/img111/1637/30765795kw5.png
现在它也绘制内部TextBox控件的背景,但UserControl的背景颜色仍然存在。有什么方法可以删除UserControl的背景画吗?
答
有很多方法可以做到这一点,但我会建议在用户控件上暴露自己的属性并绑定到用户控件的内部。例如:
<UserControl x:Name="_root" ...>
...
<Button Background="{Binding ButtonBackground, ElementName=_root}"/>
</UserControl>
另一种方法也只是到TextBox
的背景色明确设置的东西。
答
我同意肯特。有很多方法可以解决这个问题。
但是,在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>
如果你真的想利用用户控件的属性集,并让它影响到用户控制的内部,我会按照肯特的建议有一个修改。我会绑定文本框的背景,以便在用户控件上设置的任何背景画笔都可以按钮(属性值继承)流动。换句话说,TextBox的背景实际上就是你想要改变的。
<UserControl x:Name="_root" ...>
<TextBox Background="{Binding TextBoxBackground, ElementName=_root}"/>
<Button/>
</UserControl>