How do I properly bind the CommandParameter with my ContextMenu to the selected ListViewItem












0














So I have a ListView, and when I right-click a item in there I have a command setup that fires when clicking.
I want to be able to get the text that's inside the the selected item.
So I guess I want to bind the SelectedItem of the ListView as the CommandParameter



I've noticed that the ContextMenu is not in the visual tree which makes things a bit more confusing.



It's currently returning null



<ListView x:Name="PlayerListView"
Width="200"
Height="330"
VerticalAlignment="Top"
Margin="0,80,15,0"
HorizontalAlignment="Right"
Background="#252525"
VerticalContentAlignment="Center"
ItemsSource="{Binding ServerViewModel.Players}">


<ListView.ItemTemplate>
<DataTemplate DataType="{x:Type model:PlayerModel}">
<StackPanel Orientation="Horizontal"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Width="190"
Background="#222222">

<StackPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="Command One"
DataContext="{Binding DataContext,
Source={mvvm:RootObject}}"
Command="{Binding ServerViewModel.MyCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},
Path=PlacementTarget.SelectedItem}">
<MenuItem.Icon>
<Image Source="../../Assets/image.png"
RenderOptions.BitmapScalingMode="Fant"
/>
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</StackPanel.ContextMenu>

<Image Source="../../Assets/image.png"
Width="20"
Height="20"/>

<TextBlock Text="{Binding Username}"
Foreground="White"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Margin="5"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>


The command is working fine, everything is firing but it returns null, and I know it's because how the XAML is setup, but I am not sure how to traverse through the DOM



DataContext is setup like this



public MainWindow()
{
InitializeComponent();
DataContext = new BaseViewModel();
}


The RelayCommand



public class RelayCommand : ObservableObject, ICommand
{
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;

public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentException("execute");

_execute = execute;
_canExecute = canExecute;
}

public RelayCommand(Action<object> execute) : this(execute, null)
{

}

public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}

public void Execute(object parameter)
{
//This is where I debug and see that it returns null
_execute.Invoke(parameter);
}

public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}









share|improve this question



























    0














    So I have a ListView, and when I right-click a item in there I have a command setup that fires when clicking.
    I want to be able to get the text that's inside the the selected item.
    So I guess I want to bind the SelectedItem of the ListView as the CommandParameter



    I've noticed that the ContextMenu is not in the visual tree which makes things a bit more confusing.



    It's currently returning null



    <ListView x:Name="PlayerListView"
    Width="200"
    Height="330"
    VerticalAlignment="Top"
    Margin="0,80,15,0"
    HorizontalAlignment="Right"
    Background="#252525"
    VerticalContentAlignment="Center"
    ItemsSource="{Binding ServerViewModel.Players}">


    <ListView.ItemTemplate>
    <DataTemplate DataType="{x:Type model:PlayerModel}">
    <StackPanel Orientation="Horizontal"
    VerticalAlignment="Stretch"
    HorizontalAlignment="Stretch"
    Width="190"
    Background="#222222">

    <StackPanel.ContextMenu>
    <ContextMenu>
    <MenuItem Header="Command One"
    DataContext="{Binding DataContext,
    Source={mvvm:RootObject}}"
    Command="{Binding ServerViewModel.MyCommand}"
    CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},
    Path=PlacementTarget.SelectedItem}">
    <MenuItem.Icon>
    <Image Source="../../Assets/image.png"
    RenderOptions.BitmapScalingMode="Fant"
    />
    </MenuItem.Icon>
    </MenuItem>
    </ContextMenu>
    </StackPanel.ContextMenu>

    <Image Source="../../Assets/image.png"
    Width="20"
    Height="20"/>

    <TextBlock Text="{Binding Username}"
    Foreground="White"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Center"
    Margin="5"/>
    </StackPanel>
    </DataTemplate>
    </ListView.ItemTemplate>
    </ListView>


    The command is working fine, everything is firing but it returns null, and I know it's because how the XAML is setup, but I am not sure how to traverse through the DOM



    DataContext is setup like this



    public MainWindow()
    {
    InitializeComponent();
    DataContext = new BaseViewModel();
    }


    The RelayCommand



    public class RelayCommand : ObservableObject, ICommand
    {
    private readonly Action<object> _execute;
    private readonly Predicate<object> _canExecute;

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
    if (execute == null)
    throw new ArgumentException("execute");

    _execute = execute;
    _canExecute = canExecute;
    }

    public RelayCommand(Action<object> execute) : this(execute, null)
    {

    }

    public bool CanExecute(object parameter)
    {
    return _canExecute == null ? true : _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
    //This is where I debug and see that it returns null
    _execute.Invoke(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
    }
    }









    share|improve this question

























      0












      0








      0







      So I have a ListView, and when I right-click a item in there I have a command setup that fires when clicking.
      I want to be able to get the text that's inside the the selected item.
      So I guess I want to bind the SelectedItem of the ListView as the CommandParameter



      I've noticed that the ContextMenu is not in the visual tree which makes things a bit more confusing.



      It's currently returning null



      <ListView x:Name="PlayerListView"
      Width="200"
      Height="330"
      VerticalAlignment="Top"
      Margin="0,80,15,0"
      HorizontalAlignment="Right"
      Background="#252525"
      VerticalContentAlignment="Center"
      ItemsSource="{Binding ServerViewModel.Players}">


      <ListView.ItemTemplate>
      <DataTemplate DataType="{x:Type model:PlayerModel}">
      <StackPanel Orientation="Horizontal"
      VerticalAlignment="Stretch"
      HorizontalAlignment="Stretch"
      Width="190"
      Background="#222222">

      <StackPanel.ContextMenu>
      <ContextMenu>
      <MenuItem Header="Command One"
      DataContext="{Binding DataContext,
      Source={mvvm:RootObject}}"
      Command="{Binding ServerViewModel.MyCommand}"
      CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},
      Path=PlacementTarget.SelectedItem}">
      <MenuItem.Icon>
      <Image Source="../../Assets/image.png"
      RenderOptions.BitmapScalingMode="Fant"
      />
      </MenuItem.Icon>
      </MenuItem>
      </ContextMenu>
      </StackPanel.ContextMenu>

      <Image Source="../../Assets/image.png"
      Width="20"
      Height="20"/>

      <TextBlock Text="{Binding Username}"
      Foreground="White"
      HorizontalAlignment="Stretch"
      VerticalAlignment="Center"
      Margin="5"/>
      </StackPanel>
      </DataTemplate>
      </ListView.ItemTemplate>
      </ListView>


      The command is working fine, everything is firing but it returns null, and I know it's because how the XAML is setup, but I am not sure how to traverse through the DOM



      DataContext is setup like this



      public MainWindow()
      {
      InitializeComponent();
      DataContext = new BaseViewModel();
      }


      The RelayCommand



      public class RelayCommand : ObservableObject, ICommand
      {
      private readonly Action<object> _execute;
      private readonly Predicate<object> _canExecute;

      public RelayCommand(Action<object> execute, Predicate<object> canExecute)
      {
      if (execute == null)
      throw new ArgumentException("execute");

      _execute = execute;
      _canExecute = canExecute;
      }

      public RelayCommand(Action<object> execute) : this(execute, null)
      {

      }

      public bool CanExecute(object parameter)
      {
      return _canExecute == null ? true : _canExecute(parameter);
      }

      public void Execute(object parameter)
      {
      //This is where I debug and see that it returns null
      _execute.Invoke(parameter);
      }

      public event EventHandler CanExecuteChanged
      {
      add { CommandManager.RequerySuggested += value; }
      remove { CommandManager.RequerySuggested -= value; }
      }
      }









      share|improve this question













      So I have a ListView, and when I right-click a item in there I have a command setup that fires when clicking.
      I want to be able to get the text that's inside the the selected item.
      So I guess I want to bind the SelectedItem of the ListView as the CommandParameter



      I've noticed that the ContextMenu is not in the visual tree which makes things a bit more confusing.



      It's currently returning null



      <ListView x:Name="PlayerListView"
      Width="200"
      Height="330"
      VerticalAlignment="Top"
      Margin="0,80,15,0"
      HorizontalAlignment="Right"
      Background="#252525"
      VerticalContentAlignment="Center"
      ItemsSource="{Binding ServerViewModel.Players}">


      <ListView.ItemTemplate>
      <DataTemplate DataType="{x:Type model:PlayerModel}">
      <StackPanel Orientation="Horizontal"
      VerticalAlignment="Stretch"
      HorizontalAlignment="Stretch"
      Width="190"
      Background="#222222">

      <StackPanel.ContextMenu>
      <ContextMenu>
      <MenuItem Header="Command One"
      DataContext="{Binding DataContext,
      Source={mvvm:RootObject}}"
      Command="{Binding ServerViewModel.MyCommand}"
      CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},
      Path=PlacementTarget.SelectedItem}">
      <MenuItem.Icon>
      <Image Source="../../Assets/image.png"
      RenderOptions.BitmapScalingMode="Fant"
      />
      </MenuItem.Icon>
      </MenuItem>
      </ContextMenu>
      </StackPanel.ContextMenu>

      <Image Source="../../Assets/image.png"
      Width="20"
      Height="20"/>

      <TextBlock Text="{Binding Username}"
      Foreground="White"
      HorizontalAlignment="Stretch"
      VerticalAlignment="Center"
      Margin="5"/>
      </StackPanel>
      </DataTemplate>
      </ListView.ItemTemplate>
      </ListView>


      The command is working fine, everything is firing but it returns null, and I know it's because how the XAML is setup, but I am not sure how to traverse through the DOM



      DataContext is setup like this



      public MainWindow()
      {
      InitializeComponent();
      DataContext = new BaseViewModel();
      }


      The RelayCommand



      public class RelayCommand : ObservableObject, ICommand
      {
      private readonly Action<object> _execute;
      private readonly Predicate<object> _canExecute;

      public RelayCommand(Action<object> execute, Predicate<object> canExecute)
      {
      if (execute == null)
      throw new ArgumentException("execute");

      _execute = execute;
      _canExecute = canExecute;
      }

      public RelayCommand(Action<object> execute) : this(execute, null)
      {

      }

      public bool CanExecute(object parameter)
      {
      return _canExecute == null ? true : _canExecute(parameter);
      }

      public void Execute(object parameter)
      {
      //This is where I debug and see that it returns null
      _execute.Invoke(parameter);
      }

      public event EventHandler CanExecuteChanged
      {
      add { CommandManager.RequerySuggested += value; }
      remove { CommandManager.RequerySuggested -= value; }
      }
      }






      c# wpf mvvm data-binding command






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 13 '18 at 1:48









      Mark Denom

      229110




      229110
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You could bind to the the PlacementTarget (StackPanel) of the ContextMenu and then get its DataContext:



          <DataTemplate DataType="{x:Type model:PlayerModel}">
          <StackPanel Orientation="Horizontal"
          VerticalAlignment="Stretch"
          HorizontalAlignment="Stretch"
          Width="190"
          Background="#222222"
          Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListView}}">
          <StackPanel.ContextMenu>
          <ContextMenu>
          <MenuItem Header="Command One"
          Command="{Binding PlacementTarget.Tag.ServerViewModel.MyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
          CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}">
          <MenuItem.Icon>
          <Image Source="../../Assets/image.png" RenderOptions.BitmapScalingMode="Fant"/>
          </MenuItem.Icon>
          </MenuItem>
          </ContextMenu>
          </StackPanel.ContextMenu>

          <Image Source="../../Assets/image.png" Width="20" Height="20"/>

          <TextBlock Text="{Binding Username}"
          Foreground="White"
          HorizontalAlignment="Stretch"
          VerticalAlignment="Center"
          Margin="5"/>
          </StackPanel>
          </DataTemplate>





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53272611%2fhow-do-i-properly-bind-the-commandparameter-with-my-contextmenu-to-the-selected%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You could bind to the the PlacementTarget (StackPanel) of the ContextMenu and then get its DataContext:



            <DataTemplate DataType="{x:Type model:PlayerModel}">
            <StackPanel Orientation="Horizontal"
            VerticalAlignment="Stretch"
            HorizontalAlignment="Stretch"
            Width="190"
            Background="#222222"
            Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListView}}">
            <StackPanel.ContextMenu>
            <ContextMenu>
            <MenuItem Header="Command One"
            Command="{Binding PlacementTarget.Tag.ServerViewModel.MyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
            CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}">
            <MenuItem.Icon>
            <Image Source="../../Assets/image.png" RenderOptions.BitmapScalingMode="Fant"/>
            </MenuItem.Icon>
            </MenuItem>
            </ContextMenu>
            </StackPanel.ContextMenu>

            <Image Source="../../Assets/image.png" Width="20" Height="20"/>

            <TextBlock Text="{Binding Username}"
            Foreground="White"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Center"
            Margin="5"/>
            </StackPanel>
            </DataTemplate>





            share|improve this answer


























              1














              You could bind to the the PlacementTarget (StackPanel) of the ContextMenu and then get its DataContext:



              <DataTemplate DataType="{x:Type model:PlayerModel}">
              <StackPanel Orientation="Horizontal"
              VerticalAlignment="Stretch"
              HorizontalAlignment="Stretch"
              Width="190"
              Background="#222222"
              Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListView}}">
              <StackPanel.ContextMenu>
              <ContextMenu>
              <MenuItem Header="Command One"
              Command="{Binding PlacementTarget.Tag.ServerViewModel.MyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
              CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}">
              <MenuItem.Icon>
              <Image Source="../../Assets/image.png" RenderOptions.BitmapScalingMode="Fant"/>
              </MenuItem.Icon>
              </MenuItem>
              </ContextMenu>
              </StackPanel.ContextMenu>

              <Image Source="../../Assets/image.png" Width="20" Height="20"/>

              <TextBlock Text="{Binding Username}"
              Foreground="White"
              HorizontalAlignment="Stretch"
              VerticalAlignment="Center"
              Margin="5"/>
              </StackPanel>
              </DataTemplate>





              share|improve this answer
























                1












                1








                1






                You could bind to the the PlacementTarget (StackPanel) of the ContextMenu and then get its DataContext:



                <DataTemplate DataType="{x:Type model:PlayerModel}">
                <StackPanel Orientation="Horizontal"
                VerticalAlignment="Stretch"
                HorizontalAlignment="Stretch"
                Width="190"
                Background="#222222"
                Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListView}}">
                <StackPanel.ContextMenu>
                <ContextMenu>
                <MenuItem Header="Command One"
                Command="{Binding PlacementTarget.Tag.ServerViewModel.MyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
                CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}">
                <MenuItem.Icon>
                <Image Source="../../Assets/image.png" RenderOptions.BitmapScalingMode="Fant"/>
                </MenuItem.Icon>
                </MenuItem>
                </ContextMenu>
                </StackPanel.ContextMenu>

                <Image Source="../../Assets/image.png" Width="20" Height="20"/>

                <TextBlock Text="{Binding Username}"
                Foreground="White"
                HorizontalAlignment="Stretch"
                VerticalAlignment="Center"
                Margin="5"/>
                </StackPanel>
                </DataTemplate>





                share|improve this answer












                You could bind to the the PlacementTarget (StackPanel) of the ContextMenu and then get its DataContext:



                <DataTemplate DataType="{x:Type model:PlayerModel}">
                <StackPanel Orientation="Horizontal"
                VerticalAlignment="Stretch"
                HorizontalAlignment="Stretch"
                Width="190"
                Background="#222222"
                Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListView}}">
                <StackPanel.ContextMenu>
                <ContextMenu>
                <MenuItem Header="Command One"
                Command="{Binding PlacementTarget.Tag.ServerViewModel.MyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
                CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}">
                <MenuItem.Icon>
                <Image Source="../../Assets/image.png" RenderOptions.BitmapScalingMode="Fant"/>
                </MenuItem.Icon>
                </MenuItem>
                </ContextMenu>
                </StackPanel.ContextMenu>

                <Image Source="../../Assets/image.png" Width="20" Height="20"/>

                <TextBlock Text="{Binding Username}"
                Foreground="White"
                HorizontalAlignment="Stretch"
                VerticalAlignment="Center"
                Margin="5"/>
                </StackPanel>
                </DataTemplate>






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 13 '18 at 9:18









                mm8

                81.4k81831




                81.4k81831






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53272611%2fhow-do-i-properly-bind-the-commandparameter-with-my-contextmenu-to-the-selected%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Xamarin.iOS Cant Deploy on Iphone

                    Glorious Revolution

                    Dulmage-Mendelsohn matrix decomposition in Python