WPF绑定 - StringFormat - 未格式化

26

我有一个设置了值的工具提示:

Value="{Binding Path=DataItem.EquitySold, StringFormat=Reserved (Equity Share: \{0\}%)}"

这个工具提示显示为:

72

但我希望它是:

保留股份(股权份额:72%)

我的绑定出了什么问题?


我无法理解这个XAML是如何编译通过的。 - alpha-mouse
7个回答

76

工具提示是一种内容控件,这意味着它实际上没有显示模型。这在早期由@deccyclone给出的答案中通过将内容设置为TextBlock进行了演示。由于TextBox设计用于显示文本,所以StringFormat绑定属性可以按照预期工作。Button也是这样的例子。(两者均派生自ContentControl)

如果将工具提示的内容设置为字符串,则会显示该字符串,因为工具提示具有内置的转换器,如果数据类型为字符串,则可以利用该内置的字符串转换器,需要使用ContentStringFormat属性设置格式。

<ToolTip
     Content="{Binding Path=Value}"
     ContentStringFormat="{}{0:F2} M"
/>

顺便提一下,使用StringFormat或ContentStringFormat的技巧在于控件提供哪个属性来设置显示文本。 如果是Text属性,使用StringFormat; 如果是Content属性,则使用ContentStringFormat。


3
标题属性 -> 标题字符串格式 :) 谢谢! - surfen
为什么你在ContentStringFormat中首先列出了开放和关闭花括号? - ClearCloud8
@ClearCloud8Binding...,StringFormat={}{0} 中,打开和关闭大括号是必要的,当你需要 {0} 成为第一个字符时。对于 ContentStringFormat,它们不是必需的,但也可以存在。 - xmedeko

19

你试过这个吗:

<ToolTip>
    <TextBlock Text="{Binding Path=DataItem.EquitySold, StringFormat=Reserved (Equity Share: \{0\}%)}" />
</ToolTip>

1
他为什么不能使用Value属性? - Tomer W
1
@TomerW:Mitch在他的回答中解释了为什么。 - decyclone

1
<Button.ToolTip>
 <TextBlock Text="{Binding Path=ToggleText, StringFormat={}{0} Text}"/>
</Button.ToolTip>

在 DataGridTemplateColumn 中的按钮


1

您不需要转义括号。尝试这个(我喜欢将格式放在单引号中):

Value="{Binding Path=DataItem.EquitySold, StringFormat='Reserved (Equity Share: {0}%)'}"

恐怕这没有任何区别。 - David Ward

0

对于其他在稍微不同情况下到达此处的人,这是为了通过Style设置提示工具StringFormat而需要的:

<DataGridTextColumn Header="Amount" CanUserSort="True"
                                    Binding="{Binding Amount,Mode=OneWay}">
    <DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="ToolTip">
                <Setter.Value>
                    <TextBlock Text="{Binding JournalEntryId, StringFormat='Reserved (Equity Share: \{0\}%)'}" />
                </Setter.Value>
            </Setter>
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>

0

我假设这是您的数据类型所支持的 - 据我所知,它作为参数传递给IFormattable。


-1

尝试

StringFormat=Reserved (Equity Share: {0:P0})

我很抱歉,这没有任何区别。 - David Ward

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接