ElGaucho
ElGaucho

Reputation: 408

How to pass CommandParameter by Binding through XAML on customcontrols

I've generated a CustomControl that includes (among other elements) a TextBox. Binding a value works:

(Code-Snippet from Generic.xaml)

<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterValue, Mode=TwoWay }"/>

Now, i wanted to add some ValueConverter to my Binding, so i implemented a ParameterConverter. Using the Converter works also (so far), i can see the value being converted.

<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterValue, Mode=TwoWay, Converter={StaticResource ParameterConverter}}"/>

Now as my converters logic got more complex, i wanted to use the parameter Property on my ParameterConverter. But unfortunately, as parameter is no DependencyProperty, i cannot bind anything to it. I've registered some DependencyProperty in my CustomControl, but i wasn't able to bind it to the ConverterParameter in my XAML. The desired ConverterParameter i want to bind to is a Enum called ParameterUnit. What i expected the result should look like is something like this:

<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterValue, Mode=TwoWay, Converter={StaticResource ParameterConverter}, ConverterParameter='{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterUnit}'}"/>

I've got a solution, but looks really nasty and violates the CCD-principles i'd like to follow always as far as possible. I added some code in my ParameterControl-Class:

public ParameterControl()
    {
        _textBox = (TextBox)Template.FindName("ParameterValueTextBox", this);
        this.Loaded += (s, e) => SetupControl();
    }

public void SetupControl()
    {
        var textBinding = new Binding();
        textBinding.RelativeSource = RelativeSource.TemplatedParent;
        textBinding.Path = new PropertyPath("ParameterValue");
        textBinding.Converter = new ParameterToHumanFormatConverter();
        textBinding.ConverterParameter = ParameterUnit;
        textBinding.Mode = BindingMode.TwoWay;
        textBinding.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;  
        _textBox.SetBinding(TextBox.TextProperty, textBinding);
    }

Isn't there no better, cleaner and easier solution? I just can't believe there is no way to bind a ConverterParameter.

Upvotes: 0

Views: 915

Answers (1)

brunnerh
brunnerh

Reputation: 184516

If you need more than one value binding just use a MultiBinding.

Upvotes: 1

Related Questions