我在UserControl
内有ListBox
,其样式在中定义,但样式被忽略。我们在Application.Resources
中添加了一个通用ListBox
样式。为什么在控件内定义的样式被忽略?
为什么Application.Resources
样式优先于控件资源中定义的样式?
这是我如何定义ListBox
和它的风格:
<ListBox x:Name="myListBox" SelectionMode="Extended" >
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Margin="0" Padding="2" Grid.Column="0" Grid.ColumnSpan="2" x:Name="Background" CornerRadius="0" Background="Transparent" BorderThickness="0" BorderBrush="Transparent" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
<CheckBox x:Name="myCheckBox" Grid.Column="0" IsChecked="{Binding MyBoolean}"
HorizontalAlignment="Center" IsThreeState="False" VerticalAlignment="Center" Background="Transparent" Click="myCheckBox_Click"/>
<TextBlock Grid.Column="1" Text="{Binding ItemName}" VerticalAlignment="Center" Margin="4,1,2,4">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="Black" />
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
这是我们如何添加ListBox
通用的风格在App.xaml
- Application.Resources
:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MyAssembly;component/MyListBoxGenericStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
另外,如果我定义样式在ListBox.ItemContainerStyle里面好像有效:
<ListBox x:Name="myListBox" SelectionMode="Extended" >
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Margin="0" Padding="2" Grid.Column="0" Grid.ColumnSpan="2" x:Name="Background" CornerRadius="0" Background="Transparent" BorderThickness="0" BorderBrush="Transparent" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
<CheckBox x:Name="myCheckBox" Grid.Column="0" IsChecked="{Binding MyBoolean}"
HorizontalAlignment="Center" IsThreeState="False" VerticalAlignment="Center" Background="Transparent" Click="myCheckBox_Click"/>
<TextBlock Grid.Column="1" Text="{Binding ItemName}" VerticalAlignment="Center" Margin="4,1,2,4">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="Black" />
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
你能从MyListBoxGenericStyle共享ListBox风格吗? – VMaleev
@VMaleev - 当然,我刚刚添加了它。现在这很简单。 – Dzyann