2008-10-07 24 views
2

我有個用戶控件(複合控制),其可以表示爲下面的僞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的背景畫嗎?

回答

5

有很多方法可以做到這一點,但我會建議在用戶控件上暴露自己的屬性並綁定到用戶控件的內部。例如:

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

另一種方法也只是到TextBox的背景色明確設置的東西。

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> 

如果你真的想利用用戶控件的屬性集,並讓它影響到用戶控制的內部,我會按照肯特的建議有一個修改。我會綁定文本框的背景,以便在用戶控件上設置的任何背景畫筆都可以按鈕(屬性值繼承)流動。換句話說,TextBox的背景實際上就是你想要改變的。

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