2015-04-03 103 views
0

我可以申請一個背景圖片一個StackPanel與此XAML代碼:如何將StackPanel的背景設置爲樣式資源中定義的ImageBrush?

<StackPanel> 
    <StackPanel.Background> 
    <ImageBrush ImageSource="bg.png" Stretch="Uniform" AlignmentY="Bottom" /> 
    </StackPanel.Background> 
    ... 
</StackPanel> 

但是,這是一種很多時候應用於多個StackPanels鍵入的。所以我寧願定義一個Style(aka靜態資源?),我可以快速地應用到單個的StackPanels。

於是我開始寫這本:

<Window.Resources> 
    <ImageBrush x:Key="SpBg" ImageSource="bg.png" Stretch="Uniform" AlignmentY="Bottom" /> 
    <Style x:Key="StackPanelBg" TargetType="StackPanel"> 
    <!-- begin invalid xaml --> 
    <Setter Property="Background" Value="SpBg" /> 
    <!-- end invalid xaml --> 
    </Style> 
</Window.Resources> 

讓我能夠做到這一點:

<StackPanel Style="{StaticResource StackPanelBg}"> 
    ... 
</StackPanel> 

除了不工作; Setter行不正確。我該如何做這項工作?

回答

1

就像是:

<Window x:Class="WpfApplication12.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 

     <ImageBrush x:Key="SpBg" ImageSource="bg.png" Stretch="Uniform" AlignmentY="Bottom" /> 

     <Style x:Key="StackPanelBg" TargetType="StackPanel"> 
      <Setter Property="Background" Value="{StaticResource SpBg}" /> 
     </Style> 

    </Window.Resources> 

    <StackPanel Style="{StaticResource StackPanelBg}"> 

    </StackPanel> 
</Window> 
+0

哦,天哪,我已經如此接近......我真的應該得到這個自己。非常感謝。 – SoaperGEM 2015-04-03 14:00:30

相關問題