StringFormat is ignored

混江龙づ霸主 提交于 2019-11-29 05:31:19

Label does not use StringFormat but ContentStringFormat. Use it this way:

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

I'm astounded, but my tests just show that StringFormat only applies if the target d-prop is of type String. I've never noticed this before, nor heard it mentioned. I don't have more time to look into it right now, but this seems ridiculous.

Seriously, this works:

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

This does not:

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

Since Label.Content is not a String.

use Binding Converter:

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();
    }
}

Add it to Windows\UserControl resource:

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

Refer it in Menu CommandParameter binding:

<MenuItem Header="Key" CommandParameter="{Binding Converter={StaticResource commandParamConverter}, Path=PlacementTarget.Tag, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!