【问题标题】:HeaderTemplate with multiple items包含多个项目的 HeaderTemplate
【发布时间】:2012-01-11 15:27:16
【问题描述】:

我正在尝试为扩展程序编写 HeaderTemplate。到目前为止,我注意到所有示例都使用{Binding} 关键字从标题中获取数据。但是,如果 Header 中有多个控件会怎样?如何指定这些控件应插入到特定位置?

<Window.Resources>
    <Style x:Key="ExpanderStyle" TargetType="{x:Type Expander}">
        <Setter Property="HeaderTemplate">
            <Setter.Value>
                <DataTemplate>
                    <!-- what do I put in here? -->
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

<Expander Style="{StaticResource ExpanderStyle}">
    <Expander.Header>
        <StackPanel Orientation="Horizontal">
            <TextBlock>Some Text</TextBlock>
            <TextBlock Text="{Binding SomeBinding}" />
            <Button />
        </StackPanel>
    </Expander.Header>
    <Image Source="https://www.google.com/logos/2012/steno12-hp.jpg" />
</Expander>

我是否应该将我的绑定移动到样式中的HeaderTemplate 并覆盖Expander 中的Header 是什么?

【问题讨论】:

    标签: wpf templates xaml styles


    【解决方案1】:

    您可以使用ContentPresenter 将任何常用内容插入到您的模板中

    例如:

    <Style x:Key="ExpanderStyle" TargetType="{x:Type Expander}">
        <Setter Property="HeaderTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Border BorderBrush="Blue" BorderThickness="2">
                        <ContentPresenter />
                    </Border>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    

    【讨论】:

    • 我最终做了这样的事情。除了我最终给出了我的绑定名称,然后在 DataTemplate 中将它们更改为{Binding ElementName=NameIGave, Path=Text}。这样我就可以适当地设置它们的样式。
    【解决方案2】:

    Header 的属性 Content 只能包含一个对象。

    如果您将这些对象合并到一个面板中:

    <StackPanel>
        <TextBlock>Some Text</TextBlock>
        <TextBlock Text="{Binding SomeBinding}" />
        <Button />
    </StackPanel>
    

    然后在模板中你可以使用 {binding}

    【讨论】:

    • 对,那是我的帖子中的一个错误。它们位于 Expander.Header 元素的面板中。 {Binding} 标签进入什么结构?
    • {Binding} 转到项目的 DataContext。在这种情况下,它将是 StackPanel。
    • 能否请您在“”中包含哪些代码。
    • 你可以这样写:&lt;Style x:Key="ExpanderStyle" TargetType="Expander"&gt; &lt;Setter Property="HeaderTemplate"&gt; &lt;Setter.Value&gt; &lt;DataTemplate&gt; &lt;Border Background="Red"&gt; &lt;ContentControl Content="{Binding}" /&gt; &lt;/Border&gt; &lt;/DataTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt;
    • 但是有什么理由使用 DataTemplate 吗?如果您删除此属性,您将看到您在标题属性中指定的控件。
    猜你喜欢
    • 2019-07-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多