Wpf 如何恢复样式的同一实例

Wpf 如何恢复样式的同一实例,wpf,xaml,Wpf,Xaml,我只是在测试一些XAML的东西,我想知道为什么来自资源字典的样式在listbox的数据模板中使用时会被多次创建。 让我给你举个例子 <UserControl x:Class="WpfApplication1.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> &l

我只是在测试一些XAML的东西,我想知道为什么来自资源字典的样式在listbox的数据模板中使用时会被多次创建。 让我给你举个例子

<UserControl x:Class="WpfApplication1.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<ListBox ItemTemplate="{DynamicResource foo}" ItemsSource="{Binding Names}"/>

</UserControl>

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wpfApplication1="clr-namespace:WpfApplication1">
<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Dictionary1.xaml" />
        </ResourceDictionary.MergedDictionaries>
        <DataTemplate x:Key="foo">
            <TextBlock Style="{StaticResource TextBlockStyle}" Text="{Binding}" Loaded="TextBlock_Loaded"/>
        </DataTemplate>
    </ResourceDictionary>

</Window.Resources>
<wpfApplication1:UserControl1 />
</Window>

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

<Style x:Key="TextBlockStyle" TargetType="TextBlock">
    <Setter Property="Background" Value="Red" />
    <Setter Property="Foreground" Value="Pink" />
</Style>
</ResourceDictionary>

现在我在code behind中做了一个简单的测试,看看TextBlock是否具有相同的样式, 令人惊讶的是,它们中的每一个都有一个相同风格的新实例,所以如果我有50条记录,那么我就有50个相同风格的实例。 人们就是这样做的,还是有一种模式可以根据需要多次重用同一个实例

感谢您的关注:)