2013-01-03 87 views
0

WPF問題。我不知道要谷歌什麼。如何將Control和ContentControl的繼承屬性「傳遞」給UserControl中的元素?

我有一個用戶控件:

<UserControl x:Class="MyProj.MyControl" 
      x:Name="Self" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Button /> 
</UserControl> 

我用這樣的:

<local:MyControl Background="Green" /> 

但背景似乎並沒有改變。這是因爲按鈕的背景沒有改變。我想讓按鈕的背景使用usercontrol的背景。

我想我可以做到這一點:

<UserControl x:Class="MyProj.MyControl" 
      x:Name="Self" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Button Background="{Binding Path=Background, ElementName=Self" /> 
</UserControl> 

但我非常希望所有的控制和ContentControl中繼承屬性應用到按鈕(工具提示了borderThickness,BorderBrush等)。

所以我能做些什麼,而不是這樣的:

<UserControl x:Class="MyProj.MyControl" 
      x:Name="Self" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Button Background="{Binding Path=Background, ElementName=Self" 
      ToolTip="{Binding Path=ToolTip, ElementName=Self" 
      BorderThickness="{Binding Path=BorderThickness, ElementName=Self" 
      BorderBrush="{Binding Path=BorderBrush, ElementName=Self" 
      ... 
      ... 
      ... 
      ... /> 
</UserControl> 

(注:這是它承載許多控件較大的用戶控件的小(最小的我可以管理,其實)的例子。)

+0

如果你要做的就是主機一個按鈕,那麼你爲什麼不插入到你的其他XAML直接?否則,當您託管更多的控件(通常情況下),您必須按照您的示例進行操作,因爲正如您所知,控件是不尋常的。 – Davio

+0

這是一個較小的(實際上我可以管理的最小的)較大的UserControl的示例,它承載了許多控件。 – epalm

+0

它是否需要成爲一個UserControl?爲什麼不僅僅是一個樣式模板或ContentControl與您的依賴關係帶入TemplateBindings? –

回答

1

唉。那麼,簡短的回答:你不能,至少不容易。 XAML不像HTML/CSS那樣工作。 Button(並且就此而言,幾乎任何Control)默認情況下都不會從其容器繼承屬性。

可能手藝自己Button,等那些繼承了......或者,你也許可以申報Style適用於一切,並試圖抓住任何含元素的屬性(即,通過RelativeSource FindAncestor)控制。 ..或者你可以做你在做什麼:手動設置每個屬性。

Style方法的實例:

<Style TargetType="{x:Type Control}"> 
    <Setter 
     Property="Background" 
     Value="{Binding (Control.Background), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Control}}}"/> 
</Style> 
+0

是的,我認爲這會奏效。 – Davio

+0

您指的是JerKimball的三種解決方案中的哪一種? – epalm

+0

可能風格的方法,因爲我沒有真正進入其他的(我很懶,這將是很多打字) – JerKimball

相關問題