Question

I have a ListBox, each item has a TextBlock and a Button. The Button has a Command. The problem is, that the listbox's selecteditem doesn't change when I click the button. ( I guess the selectionchanged event doesn't fire). when I click the textblock, it works fine.

<ListBox ItemsSource="{Binding FavList}" SelectedItem="{Binding SelectedFav,Mode=TwoWay}">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <Grid>
                                    <TextBlock Text="{Binding Name}"/>
                                    <Button Content="+" Command="{Binding Source={StaticResource ViewModel},Path=AddToFavCommand}" Margin="120,0,0,0"/>
                                </Grid>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>

Related parts of my viewmodel ( I don't think it has any problems ):

private Products _selectedFav;
        public Products SelectedFav
        {
            get
            {
                return _selectedFav;
            }
            set
            {
                if (value != _selectedFav)
                {
                    _selectedFav = value;
                    NotifyPropertyChanged("SelectedFav");
                }
            }
        }

public DelegateCommand AddToFavCommand { get; set; }
AddToFavCommand = new DelegateCommand(addtofav);

private void addtofav(object parameter){
}

So I need to change the selected item before the command running. How can I do that?

Was it helpful?

Solution

My suggestion would be to not use a ListBox here. Only use the ListBox when you need to actually select an item. Instead, consider an ItemsControl.

The next issue you have is passing in the selected item. You can do this by binding the CommandParameter to the current item like this:

CommandParameter="{Binding}"

Then, you will need to change your Command to accept a parameter. With DelegateCommand, it looks like you're possibly using Prism (or have rolled your own DelegateCommand), and I'm not sure if you can set it up to accept a parameter. I know that for MVVM Light (and RelayCommand) it looks like this:

public RelayCommand<Products> AddToFavCommand { get; private set;}

then, where you set up your commands:

AddToFavCommand = new RelayCommand<Products>((p)=>AddToFav(p));

or, more simply, using a method group:

AddToFavCommand = new RelayCommand<Products>(AddToFav);

and

private void AddToFav(Products p)
{

     //do stuff
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top