获取ListView Ancestor的DataContext

时间:2009-05-11 21:49:57

标签: mvvm binding relativesource

我正在使用MVVM开发一个WPF应用程序并需要一些帮助。

对于我的AddressesViewModel的视图我有一个带有listview的usercontrol。我想从listViewItem的contextmenu执行AddressesViewModel中的命令。因为我打开了一个ContextMenu,所以在可视树中找不到它(我在某处读到)。

以下是View标记:

    <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>

这是ViewModel类:

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; }
}

提前致谢

1 个答案:

答案 0 :(得分:3)

如果您的MenuItem看起来像这样,它应该适合您:

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