我有ListBox和ListBoxItem的样式
<Style TargetType="{x:Type ListBox}">
<Setter Property="Background" Value="{StaticResource DarkBackground}"/>
</Style>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="{StaticResource LightBackground}"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="Margin" Value="5,0,5,0"/>
<Setter Property="Padding" Value="5,0,5,0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border Background="{TemplateBinding Background}" Height="35"
BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
<ItemsControl Focusable="False" Margin="{TemplateBinding Padding}" Foreground="{TemplateBinding Foreground}" VerticalContentAlignment="Center">
<ContentPresenter Tag="{Binding Path=Tag, RelativeSource={RelativeSource TemplatedParent}}" Content="{Binding Path=Content, RelativeSource={RelativeSource TemplatedParent}}"/>
</ItemsControl>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="{StaticResource GlassFX}"/>
<Setter Property="BorderBrush" Value="White"/>
<Setter Property="BorderThickness" Value="1"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我在MainWindow上添加了一个新的ListBox:
<ListBox ItemsSource="{Binding AvailableClient}">
<ListBox.ItemTemplate>
<DataTemplate>
<ListBoxItem Tag="{Binding Path=ID}" Content="{Binding Path=Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
但我的约束不起作用......
如果改变风格
<ContentPresenter Tag="{Binding Path=Tag.ID, RelativeSource={RelativeSource TemplatedParent}}" Content="{Binding Path=Content.Name, RelativeSource={RelativeSource TemplatedParent}}"/>
所有工作。但我需要一个适用于许多列表框的通用样式。 我怎么能这样做?
答案 0 :(得分:0)
如果您正在使用VisualStudio在解决方案中创建新的Resource Dictionary
,请将您的样式复制到其中:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type ListBox}">
-Your style code here-
</Style>
</ResourceDictionary>
然后,在您的Window / Usercontrol资源或最好是您的App.xaml文件中,加载您的资源字典,如下所示:
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="whatever you named the file.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
现在,您的自定义样式应覆盖解决方案中所有列表框的样式。如果您想在另一个解决方案中使用您的样式,只需将您创建的xaml文件放入解决方案中并像上面一样加载它。