我似乎找不到神奇的组合来使HeaderStringFormat适用于WPF扩展器。

以下是我尝试过的所有内容:

<Expander Header="{Binding Path=MyProperty, StringFormat=Stuff: ({0})}"  >
    <TextBlock Text="Some Content" />
</Expander>
<Expander HeaderStringFormat="{}Stuff ({0})" Header="{Binding Path=MyProperty}">
    <TextBlock Text="Some More Content" />
</Expander>
<Expander HeaderStringFormat="{}Stuff ({0:0})" Header="{Binding Path=MyProperty}">
    <TextBlock Text="Even More Content" />
</Expander>

我可以在代码中使格式化字符串正常工作的唯一方法是:

<Expander>
    <Expander.Header>
        <TextBlock Text="{Binding Path=MyProperty, StringFormat=Stuff: ({0})}" />
    </Expander.Header>
    <Expander.Content>
        A Expander with working header
    </Expander.Content>
</Expander>

我做错了什么?

有帮助吗?

解决方案

首先要注意的是:

  

如果您设置了HeaderTemplate或   HeaderTemplateSelector属性   HeaderedContentControl,   HeaderStringFormat属性是   忽略。    MSDN

在WPF中有很多类似的问题需要注意。您没有在您的示例中显示,但请记住它。但是,我不认为这是你的问题。

要注意的第二件事是:这与:

不一样
String.Format("My string value is: {0}", myValue");

HeaderedContentControl和HeaderStringFormat专门用于实现IFormattable的类。 HederStringFormat格式化标题,ContentStringFormat格式化内容。如果IFormattable.ToString,则任一属性的值是传递给类实现的格式。您可以阅读 MSDN 。但这是如何使其发挥作用的要点。

public class MyTestClass : IFormattable
{
    #region IFormattable Members
    public string ToString(string format, IFormatProvider formatProvider)
    {
        if(format == "n")
        {
            return "This is my formatted string";
        }
        else
        {
            return "this is my non-formatted string";
        }
    }
    #endregion
}

    <Style TargetType="{x:Type TabItem}">
        <Setter Property="HeaderStringFormat" Value="n" />
        <Setter Property="ContentStringFormat" Value="" />
    </Style>

<TabControl>
    <TabItem Header="{Binding Content, RelativeSource={RelativeSource Self}}">
        <local:MyTestClass />
    </TabItem>
</TabControl>

此TabItem现在将显示<!>“;这是我的格式化字符串<!>”;在标题中,内容将是<!>“;这是我的非格式化字符串<!>”;。

要记住几件事。通常,这些属性仅在HeaderedItemsControl上下文中使用。 HeaderStringFormat不会以这种方式绑定,而是具有HeaderedItemsControl的ItemContainer提供的默认绑定。例如,如果您设置TabItem的ItemsSource属性,那么它将自动为您添加标题和内容绑定,您所要做的就是提供所需的格式化值。

最后,但并非最不重要的是,我能够使用GroupBox和TabItem使一切正常工作,但使用扩展器并没有太多运气,我不知道为什么。扩展器正确处理ContentStringFormat,但不处理HeaderContentStringFormat。考虑到两者都继承自HeaderContentControl。

,这令人惊讶
scroll top