在XAML中覆盖控件模板属性值

时间:2014-02-04 14:37:30

标签: c# wpf xaml listbox controltemplate

我有一个ListBoxItem模板,如下所示

<Window.Resources>
    <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="Padding"
                Value="20" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Border x:Name="Bd"
                            Padding="{TemplateBinding Padding}">
                        <ContentPresenter />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

在上面的示例中,Padding默认为20。因此,名为 Bd Border控件也会获得相同的值。因此,上面的资源将使用已定义的ListboxIem替换窗口中ListBox的所有ListBox。我有一个包含ToggleButton的特定Padding也获得Padding值20.我的要求是将此ListBox边界的<ListBox Name="lb"> <ListBox.ItemTemplate> <DataTemplate> <ToggleButton IsChecked="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}"> <TextBlock x:Name="txt"> </TextBlock> </ToggleButton> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 值设为10 。有谁可以帮我这个。提前致谢

{{1}}

1 个答案:

答案 0 :(得分:0)

您可以为列表框定义一个基于原始样式的新样式,但会覆盖Padding属性。这样,将使用您为列表框显式设置的样式,而不是窗口资源中定义的样式:

<Window>
    <Window.Resources>
        <Style x:Key="listBoxItemStyle" TargetType="{x:Type ListBoxItem}">
            <Setter Property="Padding" Value="20" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListBoxItem}">
                        <Border x:Name="Bd"
                                Padding="{TemplateBinding Padding}">
                            <ContentPresenter />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource listBoxItemStyle}">
    </Window.Resources>

    <ListBox Name="lb">
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource listBoxItemStyle}">
                <Setter Property="Padding" Value="10" />
            </Style>
        </ListBox.ItemContainerStyle>

        <ListBox.ItemTemplate>
            <DataTemplate>
                <ToggleButton IsChecked="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}">
                    <TextBlock x:Name="txt">
                    </TextBlock>
                </ToggleButton>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>
相关问题