user635097
user635097

Reputation: 95

Button on a ListView - using MVVM

I have a button on a listview control. I have bound this control to one of the command on the base class of the ViewModel class. If I place a button outside of the listview it works fine with the same command. But the command does not get fired when I place it on the listview.

can you think of a reason????

Below is the snippet:

<ListView Grid.Row="2" AlternationCount="2" ItemsSource="{Binding Path=AObject}" Margin="20" MaxHeight="200">
            <ListView.DataContext>
                <local:MyViewModel/>
            </ListView.DataContext>
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Run ID" DisplayMemberBinding="{Binding Path=RID}" />
                    <GridViewColumn Header="Job ID" DisplayMemberBinding="{Binding Path=JID}" />
                    <GridViewColumn Header="Run Description">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <ContentPresenter Content="{Binding Path=OpenScCommand}" HorizontalAlignment="Right"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="Edit">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Button  Command="{Binding ShowItemCommand}" CommandParameter="{Binding Path=RID}" Content="_Edit email run" IsDefault="False"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>

Upvotes: 1

Views: 2981

Answers (3)

tdelaney
tdelaney

Reputation: 41

You can also do this with a little less code..

<Button Command="{Binding ShowItemCommand}">
    <Button.DataContext>
        <local:MyViewModel/>
    </Button.DataContext>
 </Button>

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292355

That's because the button is in the ListViewItem, so it inherits the DataContext of the item that contains it. Here's how you can bind to the DataContext of the ListView itself:

<Button  Command="{Binding ShowItemCommand}" DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType=ListView}}" ...

As a side note: depending on what the command does, it might be better to put it in the ViewModel of the items

Upvotes: 3

Elad Katz
Elad Katz

Reputation: 7591

When you put the button inside the listview it gets a new DataContext - it gets the DataContext of the current item in the list, and therefor it loses the original DataContext.

The best solution to this is using ViewModelLocator

Upvotes: 0

Related Questions