2011-09-23 24 views
1

的子控件設置樣式說我有這樣的用戶控件:爲用戶控件

<UserControl x:Class="StyleTest.UserControl1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d" 
     d:DesignHeight="300" d:DesignWidth="300"> 
<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition /> 
     <RowDefinition /> 
    </Grid.RowDefinitions> 
    <Button Grid.Row="0">Style please</Button> 
    <Button Grid.Row="1">Style please</Button> 
</Grid> 

而且我想設置的所有按鈕在此控件的背景=綠色。 但我不想影響我的程序中的其他按鈕,我不想修改控件的代碼。

我發現現在的問題是這樣的:

<Window x:Class="StyleTest.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:loc="clr-namespace:StyleTest" 
    Title="MainWindow" Height="350" Width="525"> 
<Window.Resources> 
    <Style x:Key="UserControlStyles" TargetType="Button"> 
     <Setter Property="Background" Value="green" /> 
    </Style> 
</Window.Resources> 
<Grid> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition /> 
     <ColumnDefinition /> 
    </Grid.ColumnDefinitions> 
    <Button Grid.Column="0">no Style please</Button> 
    <loc:UserControl1 Grid.Column="1"> 
     <loc:UserControl1.Resources> 
      <Style TargetType="Button" BasedOn="{StaticResource UserControlStyles}" /> 
     </loc:UserControl1.Resources> 
    </loc:UserControl1> 
</Grid> 

但是,這將意味着,我要這個代碼添加到控制的每一個實例,以及一些額外的代碼,如果我想風格例如TextBoxes的前景色也是。

我所尋找的是類似這樣的東西:

 <Style TargetType="Buttons that are childs of UserControl1"> 
     <Setter Property="Background" Value="green" /> 
    </Style> 

是否有這樣做的一種方式?

我不認爲一個控件模板就足夠了,因爲我不想重新設計整個控件,我只是想設置按鈕的顏色。

回答

6

在App.xaml中可以添加這種風格將被應用到UserControl

<Style TargetType="StyleTest:UserControl1" > 
    <Style.Resources> 
    <Style TargetType="Button"> 
     <Setter Property="Background" Value="green" /> 
    </Style> 
    </Style.Resources> 
</Style> 
+0

我修復了一些錯別字 – baalazamon

+0

謝謝,那就是我一直在尋找的東西。 – MTR

1

如果我理解正確的話,你只需要修改你的用戶控件,讓你添加的樣式出現,而不是在窗口控制

<UserControl x:Name=UserControl1 ...> 
<UserControl.Resources> 
    <Style TargetType="Button"> 
     <Setter Property="Background" Value="green" /> 
    </Style> 
</UserControl.Resources> 

我剛纔看到你說你不想修改控制。你的意思是你不能修改UserControl的xaml?爲什麼不?

+0

的所有實例,這是多還是少,有什麼我現在做的事情。但我不想將此代碼添加到此控件的每個用法。我想要有一箇中心位置(app.xaml)來爲所有此類型的控件中的所有按鈕設置樣式。 – MTR

+0

@MTR:這不是控件的所有用法,只是在控件定義內部。 – Ray

+0

我明白了。但我不想修改控件的代碼,因爲它被其他程序使用。 – MTR