【问题标题】:StringFormat is ignored忽略字符串格式
【发布时间】:2011-06-16 09:32:02
【问题描述】:


这是我的绑定(缩短,Command-Property 也绑定了)

<MenuItem Header="Key" CommandParameter="{Binding StringFormat='Key: {0}', Path=PlacementTarget.Tag, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>

ContectMenu 的 PlacementTarget 的 Tag-Property 是一个类似字符串

"Short.Plural"

我期望在命令处理程序中收到的是:

Key: Short.Plural

但我真正收到的是:

Short.Plural

【问题讨论】:

  • 您是否将此值发送到命令参数?

标签: wpf binding string-literals string-formatting


【解决方案1】:

标签不使用 StringFormat,而是使用 ContentStringFormat。以这种方式使用它:

<TextBlock x:Name="textBlock" Text="Base Text"/>
<Label Content="{Binding Path=Text, ElementName=textBlock}" ContentStringFormat="FORMATTED {0}"/>

【讨论】:

  • 这应该被标记为答案。同样对于一个 MenuItem 来格式化 Header 它是 HeaderStringFormat
【解决方案2】:

我很震惊,但我的测试表明,StringFormat 仅适用于目标 d-prop 类型为 String 的情况。我以前从未注意到这一点,也没有听说过它。我现在没有更多时间研究它,但这似乎很荒谬。

说真的,这很有效:

<TextBlock x:Name="textBlock" Text="Base Text"/>
<TextBlock Text="{Binding StringFormat=FORMATTED {0}, Path=Text, ElementName=textBlock}"/>

这不是:

<TextBlock x:Name="textBlock" Text="Base Text"/>
<Label Content="{Binding StringFormat=FORMATTED {0}, Path=Text, ElementName=textBlock}"/>

因为Label.Content 不是String

【讨论】:

  • 但是 commandparameter 似乎无法识别 stringformat 或者至少它不知道如何使用它,所以它只返回绑定中的值而不是 stringformat 的结果。
【解决方案3】:

使用绑定转换器:

public class CommandParamConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string)
        {
            return string.Format("Key {0}", value);
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

将其添加到 Windows\UserControl 资源:

<Window.Resources>
    <local:CommandParamConverter x:Key="commandParamConverter" />
</Window.Resources>

在菜单命令参数绑定中引用它:

<MenuItem Header="Key" CommandParameter="{Binding Converter={StaticResource commandParamConverter}, Path=PlacementTarget.Tag, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>

【讨论】:

  • 好的,这似乎是目前唯一的解决方案...我将使用转换器,但使用 ConverterParameter => "StringConcatenationConverter"
  • @tabina 的回答更适合这个,因为它不仅消除了对额外转换器的要求,而且还具有更容易应用本地化的好处
猜你喜欢
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
  • 1970-01-01
  • 2019-11-18
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 2016-07-30
相关资源
最近更新 更多