自定义HeaderedContentControl,使用multibinding设置标头

时间:2013-06-17 08:32:12

标签: c# wpf xaml multibinding

我正在做一个自定义HeaderedContentControl,其基本上是这样的样式:

<Style TargetType="{x:Type controls:DetailsControl}">
    <Style.Resources>
        <!-- Only if content is string provide a default Template -->
        <DataTemplate DataType="{x:Type system:String}">
            <TextBlock Text="{TemplateBinding Content}"
                       FontSize="{DynamicResource NormalFontSize}" />
        </DataTemplate>
    </Style.Resources>
    <Setter Property="HeaderTemplate">
        <Setter.Value>
            <DataTemplate DataType="{x:Type system:String}">
                <TextBlock Text="{TemplateBinding Content}"
                           FontWeight="Light"
                           FontSize="{DynamicResource SubHeaderFontSize}"/>
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Template" Value="{StaticResource DetailsControlTemplate}" />
</Style>

<ControlTemplate x:Key="DetailsControlTemplate"
                 TargetType="{x:Type controls:DetailsControl}">
    <StackPanel>
        <ContentPresenter ContentSource="Header"
                          ContentTemplate="{TemplateBinding HeaderTemplate}"/>

        <ContentPresenter ContentSource="Content"
                          ContentTemplate="{TemplateBinding ContentTemplate}"/>
    </StackPanel>
</ControlTemplate>

当我将标题设置为字符串

时,这很好用
<controls:DetailsControl Header="Header Text" [...]>
    [...]
</controls:DetailsControl>

或正常绑定

<controls:DetailsControl Header="{Binding SelectedItem.Name, ElementName=ElementList}" [...]>
    [...]
</controls:DetailsControl>

但是当我将Header设置为Multibinding时,它根本不会显示任何内容。

<controls:DetailsControl [...]>
    <controls:DetailsControl.Header>
        <MultiBinding StringFormat="{}{0} - {1}">
            <Binding ElementName="ElementList" Path="SelectedItem.Name"/>
            <Binding ElementName="ElementList" Path="SelectedItem.Description"/>
        </MultiBinding>
    </controls:DetailsControl.Header>

    [...]
</controls:DetailsControl>

我在哪里做错了?解决这个问题的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

StringFormat要求目标为string类型。由于Header是内容字段,请尝试将其放入TextBlock

<controls:DetailsControl.Header>
   <TextBlock>
      <TextBlock.Text>
         <Multibinding .../>
      </TextBlock.Text>
   </TextBlock>
</controls:DetailsControl.Header>