2012-01-13 41 views
4

我想用在幾個地方下面的代碼段(從https://stackoverflow.com/a/3675110/782880找到)在我的應用程序。而不是到處複製/粘貼,我怎麼能把它放在一個地方,並在各種XAML文件中引用特定的列表框(按鍵?)?如何在整個WPF應用程序中重用樣式?

<ListBox....> 
    <ListBox.Resources> 
      <Style TargetType="ListBoxItem"> 
       <Setter Property="Template"> 
        <Setter.Value> 
         <ControlTemplate TargetType="ListBoxItem"> 
          <Border Name="Border" Padding="2" SnapsToDevicePixels="true"> 
           <ContentPresenter /> 
          </Border> 
          <ControlTemplate.Triggers> 
           <Trigger Property="IsSelected" Value="true"> 
            <Setter TargetName="Border" Property="Background" 
              Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/> 
           </Trigger> 
          </ControlTemplate.Triggers> 
         </ControlTemplate> 
        </Setter.Value> 
       </Setter> 
     </Style> 
    </ListBox.Resources> 
</ListBox> 

回答

7

你可以把它變成一個資源集合在適當的水平。例如,如果您想要應用程序範圍,請將其放入App.xaml

E.g.

<Application 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    StartupUri="MainWindow.xaml" 
    > 

<Application.Resources> 
    <Style TargetType="ListBoxItem"> 
    <Setter Property="Template"> 
     ...      
    </Setter> 
    </Style> 
</Application.Resources> 

</Application> 

你可以給你的資源鍵,然後使用適當的鍵設置適當的Style屬性。通過關鍵

<Style x:Key="MyStyle" TargetType="ListBoxItem"> 

,並使用資源:與關鍵定義你的風格

<ListBox x:Name="lstItems" ItemContainerStyle="{StaticResource MyStyle}"> 
+0

啊... ItemContainerStyle就是在做我的泰。 – WhiskerBiscuit 2012-01-13 13:17:40

相關問題