views:

77

answers:

1

Hi everybody,

I have very strange issue. In my WP7 app I have a pivot control and an item template defined inside it(or in the resources, I have tried both ways, but still same issue). In the template I have a regular button with EventToCommand defined(EventName="Click"). I also have the same copy-pasted button outside the Pivot. The problem is that the button, which is outside the pivot is working ok, but the one inside doesn't work. Actually I have noticed, that any command inside my pivot doesn't work. I am handling correctly the Command in the ViewModel, because the same button, but outside the pivot is working great. Any ideas what might be the problem? Help, please. Thanks in advance. Cheers.

P.S. My code is pretty standard, but just in case here it is:

    <controls:Pivot Grid.Row="0"
        x:Name="PivotControl"
        Title="{Binding ApplicationTitle}"                         
        ItemsSource="{Binding BlaBla}">

        <controls:Pivot.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                   <Button Content="Click Me">
                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="Click">
                                <cmd:EventToCommand Command="{Binding MyCommand, Mode=OneWay}" CommandParameterValue="Test"/>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>
                    </Button>
           ...

And the ViewModel code:

public RelayCommand<string> MyCommand
    {
        get;
        private set;
    }
//And in the constructor ...
MyCommand= new RelayCommand<string>((param) => HandleTheCommand(param));

...

Thanks again.

A: 

Because you are inside the ItemTemplate of the control the DataContext that you are binding to is not your ViewModel. The Binding {Binding MyCommand, OneWay} is attempting to find the property MyCommand on an object from collection BlaBla. This is one of the limitations of the command pattern in that inside DataTemplates your DataContext is often not your ViewModel.

There really is no good way around it. You could include your command in the objects in the BlaBla collection. You could also right your own trigger that searches up the VisualTree for your ViewModel and then retrieves the command via reflection instead of an actual binding.

Stephan
Thank you Stephan, really good answer. Cheers.
Tech0