views:

737

answers:

1

I need to have a command handler for a ToggleButton that can take multiple parameters, namely the IsChecked property of said ToggleButton, along with a constant value, which could be a string, byte, int... doesn't matter.

I found this great question on SO and followed the answer's link and read up on MultiBinding and IMultiValueConverter. It went really smoothly until I had to write the MultiBinding, when I realized that I also need to pass a constant value and couldn't do something like

<Binding Value="1" />

I then came across another similar question that Kent Boogaart answered, and then I started to think about ways that I could get around this.

One possible way is to not use MVVM and simply add the Tag property to my ToggleButton, in which case my MultiBinding would look like this:

<MultiBinding Converter="{StaticResource MyConverter}">
    <MultiBinding.Bindings>
        <Binding Path="IsChecked" />
        <Binding Path="Tag" />
    </MultiBinding.Bindings>
</MultiBinding>

Kent had made a comment along the lines of, "if you're using MVVM you should be able to get around this issue". However, I'm not sure that's an option for me, even though I have adopted MVVM as my WPF pattern of necessity choice.

The reason why I say this is that I have wayyyy more than one ToggleButton in the UserControl, and each of the ToggleButtons' Commands need to call the same function. But since they are ToggleButtons, I can't use the property bound to IsChecked in the ViewModel, because I don't know which one was last clicked. I suppose I could add another private property to keep track of this, but it seems a little silly. As far as the constant goes, I could probably get rid of this if I did the tracking idea, but not sure of any other way to get around it.

Does anyone have good suggestions for me here? :)

EDIT -- ok, so I need to update my bindings, which still don't work quite right:

    <ToggleButton Tag="1" Command="{Binding MyCommand}" Style="{StaticResource PassFailToggleButtonStyle}" HorizontalContentAlignment="Center" Background="Transparent" BorderBrush="Transparent" BorderThickness="0">
        <ToggleButton.CommandParameter>
            <MultiBinding Converter="{StaticResource MyConverter}">
                <MultiBinding.Bindings>
                    <Binding Path="IsChecked" RelativeSource="{RelativeSource Mode=Self}" />
                    <Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}" />
                </MultiBinding.Bindings>
            </MultiBinding>
        </ToggleButton.CommandParameter>
    </ToggleButton>

IsChecked was working, but not Tag. I just realized that Tag is a string... duh. It's working now! The key was to use a RelativeSource of Self.

A: 

As explained above, I figured it out. I had to use Self for RelativeSource and that did the trick.

Dave