开发者

WPF MVVM: how to create & show a context menu?

开发者 https://www.devze.com 2023-01-07 20:31 出处:网络
For my WPF application I\'m usin开发者_如何学Gog MVVM, and now I want to show a generated context menu when the user right-clicks on something.

For my WPF application I'm usin开发者_如何学Gog MVVM, and now I want to show a generated context menu when the user right-clicks on something.

Routing the right-click to some action was easy, but how do I show a contextmenu which items are generated by the ViewModel?

I don't even have an idea where to start to display a context menu, since I do not have direct access to the view in MVVM.


Apologies for the delay in replying, had to have a bit of an experiment to get it to work. Give the following code a go. I just set up my own rubbish data source just so I could display some sort of data. It only displays if I right click over the first column heading and no where else... which I think is what you want, right? Let me know how you get on...any probs will continue to have a think.

   <Grid>
    <ListView Margin="8,8,33,12"  ItemsSource="{Binding Source={StaticResource Stuff}, Path=MyCollection}">
        <ListView.View>
        <GridView>
                <GridViewColumn Width="100" DisplayMemberBinding="{Binding}">
                    <GridViewColumnHeader>ProductName
                        <GridViewColumnHeader.ContextMenu>
                            <ContextMenu Name="MyMenu">
                                <MenuItem Header="Sort by..."/>
                                <MenuItem Header="Follow link..."/>
                            </ContextMenu>
                        </GridViewColumnHeader.ContextMenu>
                    </GridViewColumnHeader>
                </GridViewColumn>
                <GridViewColumn Width="100" Header="Product Name" DisplayMemberBinding="{Binding Path=Length}"/>
        </GridView>
        </ListView.View>
    </ListView>
</Grid>


If, for example, you wanted to show a ContextMenu over a DataGrid that maybe showed sales you could do this:

            <y:DataGrid.ContextMenu>
            <ContextMenu>
                <MenuItem Name="cmNewSales" Foreground="Black" Command={Binding Path=MyCommand}/>


            </ContextMenu>
        </y:DataGrid.ContextMenu>

where the MyCommand is a Command property exposed by the ViewModel, or create an ObservableCollection of commands in the ViewModel, which are exposed and bound to in the ItemSource property of the ContextMenu.

Hope that helps


The off-the-top-of-my-head answer would be to have a list of commands (corresponding to the items in your context menu) in the VM. Bind the ContextMenu's ItemSource to the VM.ListOfCommands. Use Styles as per taste.

Here's an example on the same lines... http://www.julmar.com/blog/mark/2009/04/21/UsingMVVMWithMenusInWPF.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消