views:

495

answers:

1

I am developing a WPF app using MVVM and need some help.

for the View of my AddressesViewModel I have a usercontrol with a listview. I would like to execute a command found in the AddressesViewModel from the contextmenu of the listViewItem. Because I'm opening a ContextMenu it is not found in the visual tree(I read that somewhere).

Here is the View markup:

    <UserControl>
        <ListView Name="lstAddress"
                        ItemsSource="{Binding Path=Addresses}" 
                        HorizontalAlignment="Stretch" MinHeight="150" MinWidth="100">
            <ListView.Resources>
                <ContextMenu x:Key="ItemContextMenu">
                    <MenuItem Header="Add Address"/>
                </ContextMenu>
            </ListView.Resources>
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Address" DisplayMemberBinding="{Binding Path=Address}/>
                    <GridViewColumn Header="City" DisplayMemberBinding="{Binding Path=City}"/>
                </GridView>
            </ListView.View>
            <ListView.ItemContainerStyle>
                <Style TargetType="{x:Type ListViewItem}">
                    <Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}"/>
                </Style>
            </ListView.ItemContainerStyle>
        </ListView>
    </UserControl>

Here is the ViewModel classes:

public class AddressesViewModel
{
    public List<AddressViewModel> Addresses { get; set; }

    public ICommand AddAddressCommand { get; set; }
}

public class AddressViewModel
{
    public String Address { get; set; }
    public String City { get; set; }
    public String State { get; set; }
    public String Zip { get; set; }
}

Thanks in advance

+2  A: 

If your MenuItem looks like this, it should work for you:

                <MenuItem Header="Add Address" 
                          Command="{Binding DataContext.AddAddressCommand, 
                                RelativeSource={RelativeSource FindAncestor, 
                                    AncestorType={x:Type ListView}}}"/>
pduncan