2013-07-29 119 views
3

我有一個包含一個按鈕用戶控件:反轉繼承

<Button Content="Button"/> 

和樣式:

<Style TargetType="Button"> 
    <Setter Property="Background" Value="Blue"/> 
</Style> 

父窗口(或其他用戶控件)可以設置另一個更一般風格:

<Style TargetType="Button"> 
    <Setter Property="Background" Value="Red"/> 
</Style> 

結果是(很明顯),父按鈕將有更多的一般風格(紅色)和我的你ser控制將具有更具體風格的按鈕(藍色)。


我不知道如何反轉這種行爲,以達到類似的設置在我的自定義用戶控件的默認風格,可以在家長控制或窗口,然後根據需要重寫?

的關鍵是,默認樣式首先被定義在自定義用戶控件,它是其父重寫全自動。這就是我稱之爲倒置的方式。


解決方案的假想例子maight如下所示:

<Style TargetType="Button" StylePriority="Default"> 
    <Setter Property="Background" Value="Blue"/> 
</Style> 

StylePriority可能表明,如果有該按鈕定義任何其他樣式,則默認樣式應適用於它。

+1

如果你想在父控制中使用默認樣式,爲什麼還要在'usercontrol'中再次定義另一個樣式呢? – Bolu

+0

@Bolu:編輯以更好地理解。我想在用戶控件中定義默認樣式,但是我希望能夠在父窗口中覆蓋它。讓我們說:藍色按鈕作爲在自定義控件中定義的defult。覆蓋父窗口中的紅色按鈕。 –

+0

我不是100%確定,但我不認爲有一個簡單的方法來做你想做的事情就像反轉VisualTree :) – WiiMaxx

回答

6

您可以使用動態資源。

一個用戶控件:

<UserControl x:Class="Example.UserControl1" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:local="clr-namespace:Example"> 
    <UserControl.Resources> 
     <Style TargetType="local:UserControl1"> 
      <Style.Resources> 
       <Style TargetType="Button" x:Key="UserControl1.DefaultButtonStyle"> 
        <Setter Property="Background" Value="Red"/> 
       </Style> 
      </Style.Resources> 
     </Style> 
    </UserControl.Resources> 

    <Button Content="UserControlButton" Style="{DynamicResource UserControl1.DefaultButtonStyle}"/> 
</UserControl> 

和窗口:

<Window x:Class="Example.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:Example"> 

    <Window.Resources> 
     <Style TargetType="Button"> 
      <Setter Property="Background" Value="Blue" /> 
     </Style> 
    </Window.Resources> 

    <StackPanel> 
     <local:UserControl1 > 
      <local:UserControl1.Resources> 
       <Style x:Key="UserControl1.DefaultButtonStyle" TargetType="Button" 
        BasedOn="{StaticResource {x:Type Button}}"> 
        <Setter Property="FontSize" Value="40" /> 
       </Style> 
      </local:UserControl1.Resources> 
     </local:UserControl1> 
     <Button Content="WindowButton" /> 
    </StackPanel> 
</Window> 

如果刪除在窗口的控制風格,默認的用戶控制按鈕樣式將被應用。

1

UserControl中爲按鈕顏色創建一個依賴屬性,然後綁定到它。您可以爲該屬性指定藍色的默認值。

public static readonly DependencyProperty ButtonColorProperty = 
    DependencyProperty.Register("ButtonColor", typeof(Color), typeof(MyUserControl), 
    new PropertyMetadata(Colors.Blue)); 

public Color State 
{ 
    get { return (Color)this.GetValue(ButtonColorProperty); } 
    set { this.SetValue(ButtonColorProperty, value); } 
} 

<UserControl ... 
      x:Name="root"> 
    <Button Content="Button" Background="{Binding ElementName=root, Path=ButtonColor}" /> 
</UserControl> 

然後將該屬性設置爲紅色,在那裏您要使用UserControl

<local:MyUserControl ButtonColor="Red" /> 
+4

你可以給一個簡短的代碼示例嗎? –