簡體   English   中英

覆蓋XAML中的控件模板屬性值

[英]Override Control Template Property value in XAML

我有一個如下的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。 因此,名為BdBorder控件也將獲得相同的值。 因此,以上資源將用定義的值替換我窗口中所有ListBoxListboxIem 我有一個包含ToggleButton的特定ListBox ,它也獲得了Padding值20。我的要求是針對此特定ListBox邊框將Padding值設為10。 誰能幫我這個忙。 提前致謝

<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>

您可以為列表框定義一個新樣式,該樣式將基於原始樣式,但會覆蓋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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM