Steve M
Steve M

Reputation: 9794

Formatting a CommandParameter String in WPF

I would like CommandParameter to be "9" and not "_9".

<Button Content="_9"
        Focusable="False"
        Command="{Binding NumberPress}"
        CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Content}"
        Style="{DynamicResource NumberButton}"
        Margin="92,134,92,129" />

I know I could just do CommandParameter="9" but I would like to pull out a Style to apply to multiple buttons. I have tried using StringFormat= but can't seem to make it work. Is there a way to do this without resorting to code behind?

Upvotes: 0

Views: 1539

Answers (2)

Tor Langlo
Tor Langlo

Reputation: 191

If you can modify the Command referenced by NumberPress, then the easiest solution would be to do parse the command parameter there to get the number. If that's not an option, then another solution is to create an IValueConverter class and add it to the CommandParameter binding.

<Button Content="_9"
        Focusable="False"
        Command="{Binding NumberPress}"
        CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self},
                 Path=Content, Converter={StaticResource NumberConverter}}"
        Margin="92,134,92,129" />

Implementation:

public class NumberConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is string)
        {
            string strVal = ((string)value).TrimStart('_');
            int intVal;
            if (int.TryParse(strVal, out intVal))
                return intVal;
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }
}

Upvotes: 0

Viv
Viv

Reputation: 17388

If your "_" as you mention in your comment is strictly part of View only, then you can indeed use a Format property to get that to appear for Content with ContentStringFormat.

say something like:

<Button Margin="92,134,92,129"
        Command="{Binding NumberPress}"
        CommandParameter="{Binding Content,
                                   RelativeSource={RelativeSource Self}}"
        Content="9"
        ContentStringFormat="_{0}"
        Focusable="False"
        Style="{DynamicResource NumberButton}" />

That way if you have the Button's Content Binding to a value, you do not have to keep prepending "_" there.

Upvotes: 2

Related Questions