Gorgo.Live.ToString()

Mariusz, Gorzoch tech Blog

Metro UI Multibinding

leave a comment »

Recently I came to a problem when I had to pass more then one parameter to the command (textbox control and two string configuration values). That can be achieve in WPF quite easily thru “MultiBinding” (more about that can be found under below URL: http://stackoverflow.com/questions/1350598/passing-two-command-parameters-using-a-wpf-binding). Unfortunately that approach is not available in Metro.

As I need that quite much, then I start trying with different options and found below one working quite fine. The idea is to use “Converter” and “ConverterParameter” attribute and pass thru it additional parameters in form of a string. Doing that and merging those two string parameters with original parameter pass thru CommandParameter into one array I manage to pack all parameters and pass them to OnExecute method of the command.

Below you can find example of button declaration with use that approach:

<Button Command="{Binding ShowWindow}"
        CommandParameter="{Binding ElementName=TextControl01,
            Converter={StaticResource InjectParametersConverter},
            ConverterParameter=’Param1Value|Param2Value’}"
        Content="Show phrases"></
Button>

<TextBox x:Name="TextControl01"/>

To make above work we need converter “InjectParametersConverter”:

public class InjectDefintion
{
    public TextBox TextControl { get; set; }
    public string Parameter1 { get; set; }
    public string Parameter2 { get; set; }
}

public class InjectParametersConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var parameters = ((string) parameter).Split(‘|’);
        return new InjectDefintion()
               {
                   TextControl = (TextBox) value,
                   Parameter1 = parameters[0],
                   Parameter2 = parameters[1]
               };
    }

}

and then in the OnExecute for command “ShowWindow” use paramters “InjectDefinition” to extract all parameters:

public RelayCommand<InjectDefintion> ShowWindow { get; private set; }
private void OnShowWindow(InjectDefintion paraemters)
{

                   TextControl = (TextBox) value,
                   Parameter1 = parameters[0],
                   Parameter2 = parameters[1]

}

that should give you option to pass additional parameters.

Advertisements

Written by Mariusz Gorzoch

21 July 2014 at 11:57

Posted in Bez kategorii

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: