0

The title pretty much sums it up. I've been trying to use the button's CommandParameter but I'm not sure what it should be and what additional code I need in my ViewModel class. Any help would be appreciated.

XAML:

<ItemsControl>
    <StackPanel Orientation="Horizontal">
        <Button Command="{Binding ButtonClick}" Width="150" Margin="5" Height="22" HorizontalAlignment="Left">Click</Button>
    </StackPanel>
    <ListView Name="listView" Grid.Row="1" BorderThickness="0" ItemsSource="{Binding myObjects}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Space ID" DisplayMemberBinding="{Binding ID}" Width="Auto" />
            </GridView>
        </ListView.View>
    </ListView>
</ItemsControl>

ViewModel C#:

    public ICommand ButtonClick
    {
        get { return new DelegateCommand(BtnClick); }
    }

    private void BtnClick()
    {
        //Access selected object of type myObject here.
    }

DelegateCommand class:

public class DelegateCommand : ICommand
{
    private readonly Action _action;

    public DelegateCommand(Action action)
    {
        _action = action;
    }

    public void Execute(object parameter)
    {
        _action();
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }
}
yellavon
  • 2,821
  • 12
  • 52
  • 66

2 Answers2

1

You can bind the ListView's SelectedItem to a property of your viewmodel. Like the way you bind 'myObjects' with the ItemsSource.

Eben
  • 554
  • 3
  • 11
0

I solved this by making a couple of changes. Firstly, my Delegate ICommand class could not support this behavior, so I modified it to the one listed here. Then I updated my XAML and ViewModel.

Updated XAML:

<StackPanel Orientation="Horizontal">
    <Button Command="{Binding Command1}" CommandParameter="{Binding ElementName=listView}" Width="150" Margin="5" Height="22" HorizontalAlignment="Left">Button1</Button>
</StackPanel>
<ListView Name="listView" ItemsSource="{Binding myObjects}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}" Width="Auto" />
        </GridView>
    </ListView.View>
</ListView>

Updated ViewModel:

public ICommand Command1 { get; set; }

public MainWindowViewModel()
{
    this.Command1 = new DelegateCommand(ExecuteCommand1, CanExecuteCommand1);
}

    public bool CanExecuteCommand1(object parameter)
    {
        return true;
    }

    private void ExecuteCommand1(object parameter)
    {
        ListView listView = parameter as ListView;

        foreach (MyObject myObject in listView.SelectedItems)
        {
            // Do stuff.
        }
    }
Community
  • 1
  • 1
yellavon
  • 2,821
  • 12
  • 52
  • 66