Get DataContext of ListView ancestor

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

to view my AddressesViewModel I have a usercontrol with a listview. I would like to execute the command found in AddressesViewModel from the context menu of the listViewItem. Since I open the ContextMenu, it is not found in the visual tree (I read this 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 are 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

+1


a source to share


1 answer


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}}}"/>

      

+3


a source







All Articles