WPF Context Menus in Caliburn Micro

纵饮孤独 提交于 2019-11-30 06:51:22

Using the information I found on the Caliburn Micro site I modified your XAML to look like this:

  <Grid Background="White" HorizontalAlignment="Stretch" Height="200" Name="GridLayout">       
    <ListBox x:Name="ListBoxItems">            
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Tag="{Binding DataContext, ElementName=GridLayout}">
                    <Grid.ContextMenu>
                        <ContextMenu Name="cm" cal:Action.TargetWithoutContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
                            <MenuItem Header="Open" 
                              cal:Message.Attach="Open($dataContext)">
                            </MenuItem>
                        </ContextMenu>
                    </Grid.ContextMenu>

                    <TextBlock VerticalAlignment="Center" >
                .. text..
                    </TextBlock>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

And my view model:

    public List<string> ListBoxItems { get; set; }
    public ShellViewModel()
    {
        ListBoxItems = new List<string> {"One", "Two", "Three"};          
    }

    public void Open(object source)
    {
        MessageBox.Show((string) source);
    }

Open was successfully called with the appropriate strings from the list box.

Adding to Jason's answer, if you're going to be using the same data context as the control, then you can just bind the DataContext instead of a Tag

<Grid>
    <Grid.ContextMenu>
        <ContextMenu cal:Action.TargetWithoutContext="{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
            <MenuItem Header="Open" 
                      cal:Message.Attach="Open($source)">
            </MenuItem>
        </ContextMenu>
    </Grid.ContextMenu>
</Grid>

$source The actual FrameworkElement that triggered the ActionMessage to be

You can see more info about the $source convention in here: https://caliburnmicro.com/documentation/cheat-sheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!