C# 带有syle和Datatemplate的列表框
我有ListBox和ListBoxItem的样式C# 带有syle和Datatemplate的列表框,c#,wpf,C#,Wpf,我有ListBox和ListBoxItem的样式 <Style TargetType="{x:Type ListBox}"> <Setter Property="Background" Value="{StaticResource DarkBackground}"/> </Style> <Style TargetType="{x:Type ListBoxItem}"> <Setter Prope
<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>
我正在主窗口上添加一个新的列表框:
<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}}"/>
所有的工作。但我需要一个通用的风格为许多列表框。
我该怎么做呢?如果您正在使用VisualStudio,请在解决方案中创建一个新的
资源字典
,然后将您的样式复制到其中,如下所示:
<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>
-你的风格代码在这里-
然后,在Windows/Usercontrol资源中,或者最好在App.xaml文件中,按如下方式加载资源字典:
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="whatever you named the file.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
现在,您的自定义样式应该覆盖解决方案中所有列表框的样式。如果您想在另一个解决方案中使用您的样式,只需将您创建的xaml文件放入您的解决方案中,并按照上面的方式加载即可。那么为什么不创建一个
用户控件呢?
?我需要一个统一的样式,这样它就可以在其他项目中使用。您可以在您想要的任何项目中使用用户控件,但它不适合我:)嗯……祝您好运:)