如何在WPF应用程序中重复使用样式?

5

我想在我的应用程序中的多个位置使用以下片段(来自https://dev59.com/u3RC5IYBdhLWcg3wMd9S#3675110)。不要每次都复制/粘贴,我该如何将其放在一个地方,并为各种XAML文件中的特定列表框(通过键引用)进行引用?

<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> 
1个回答

10
你可以将它放置在适当级别的资源集合中。例如,如果你想要应用程序范围,则将其放置在 App.xaml 中。

例如:

<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属性,例如,使用键定义您的样式:

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

通过关键字使用资源:

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

啊... ItemContainerStyle 就是让我无从下手的地方。谢谢。 - WhiskerBiscuit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接