在WPF中正确设置列表框的样式

时间:2013-12-27 19:55:04

标签: c# wpf xaml listbox

我正在努力使用XAML来设置列表框的样式,因为当我应用我的样式时,列表框中的所有内容都会消失。我正在应用这种风格:

<Style x:Key="ListBoxStyle" TargetType="{x:Type ListBox}">
    <Setter Property="OverridesDefaultStyle" Value="True" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <Border BorderBrush="#2a82bb" BorderThickness="1" Background="White">
                    <ContentPresenter/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

使用以下方法在我的列表项中调用它:

Style="{StaticResource ListBoxStyle}"

是否有必要进入内容展示器标记或者我还需要单独设置每个列表项的样式,因为我要覆盖列表框的默认样式?任何例子都会很棒,因为MSDN网站上的那些都没有解释过。

2 个答案:

答案 0 :(得分:1)

ListBox是项控件,因此当您创建模板而不是ContentPresenter时,请使用ItemsPresenter

<ControlTemplate>
   <Border BorderBrush="#2a82bb" BorderThickness="1" Background="White">
      <ItemsPresenter/>
   </Border>
</ControlTemplate>

答案 1 :(得分:0)

试试这个

<Style x:Key="ListBoxStyle" TargetType="{x:Type ListBox}">
        <Setter Property="OverridesDefaultStyle" Value="True" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Grid>
                    <Border BorderBrush="#2a82bb" BorderThickness="1" Background="White"/>                       
                    <ContentPresenter/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
相关问题