WPF-HeaderStringFormat不';不能在扩展器中工作
我似乎找不到让HeaderStringFormat为WPF扩展器工作的神奇组合 以下是我尝试过的所有东西:WPF-HeaderStringFormat不';不能在扩展器中工作,wpf,data-binding,string-formatting,Wpf,Data Binding,String Formatting,我似乎找不到让HeaderStringFormat为WPF扩展器工作的神奇组合 以下是我尝试过的所有东西: <Expander Header="{Binding Path=MyProperty, StringFormat=Stuff: ({0})}" > <TextBlock Text="Some Content" /> </Expander> <Expander HeaderStringFormat="{}Stuff ({0})" Heade
<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属性 头戴式内容控制 HeaderStringFormat属性为 忽略。 WPF中有很多类似的陷阱需要注意。你没有在你的例子中说明这一点,但请记住这一点。然而,我不认为这是你的问题 第二点要注意的是,这与:
String.Format("My string value is: {0}", myValue");
HeaderedContentControl和HeaderStringFormat专门用于实现IFormattable的类。HederStringFormat格式化标题,ContentStringFormat格式化内容。两个属性的值都是传递给类实现的格式(如果是IFormattable.ToString)。您可以阅读上的完整示例。但以下是如何让它发挥作用的要点
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>
公共类MyTestClass:IFormattable
{
#区域可附加成员
公共字符串到字符串(字符串格式,IFormatProvider formatProvider)
{
如果(格式==“n”)
{
返回“这是我的格式化字符串”;
}
其他的
{
返回“这是我的非格式化字符串”;
}
}
#端区
}
此选项卡项现在将在标题中显示“这是我的格式化字符串”,内容将是“这是我的非格式化字符串”
有几件事需要记住。通常,这些属性仅在HeaderEditMsControl上下文中使用。HeaderStringFormat将不会以这种方式绑定,而是由HeaderEditMsControl的ItemContainer提供默认绑定。例如,如果您设置TabItem的ItemsSource属性,那么它将自动为您连接标题和内容绑定,您所要做的就是提供所需的格式值
最后,但并非最不重要的一点是,我能够使用GroupBox和TabItem使一切正常工作,但使用扩展器就没那么幸运了,我不知道为什么。扩展器可以正确处理ContentStringFormat,但不能正确处理HeaderContentStringFormat。考虑到两者都继承自HeaderContentControl,这是令人惊讶的