25


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

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

ContectMenu 的 PlacementTarget 的标签属性是一个类似的字符串

"Short.Plural"

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

Key: Short.Plural

但我真正收到的是:

Short.Plural
4

3 回答 3

35

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

<TextBlock x:Name="textBlock" Text="Base Text"/>
<Label Content="{Binding Path=Text, ElementName=textBlock}" ContentStringFormat="FORMATTED {0}"/>
于 2012-11-15T16:05:56.257 回答
24

我很震惊,但我的测试表明,StringFormat仅当目标 d-prop 是 type 时才适用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.

于 2011-06-16T10:43:19.207 回答
1

使用绑定转换器:

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}}"/>
于 2011-06-16T11:35:22.163 回答