WPF Context Menus in Caliburn Micro

前端 未结 2 2048
旧巷少年郎
旧巷少年郎 2020-12-29 08:39

I\'m trying to get a context menu within a ListBox ItemTemplate to call a method on the parent view model, passing in the item that was clicked on as a parameter. I have thi

相关标签:
2条回答
  • 2020-12-29 09:09

    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

    0 讨论(0)
  • 2020-12-29 09:10

    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.

    0 讨论(0)
提交回复
热议问题