Reputation: 65
My WPF C# program has a listbox that holds items that the user can manipulate: changing the order, copy/paste, etc. Currently, when I select an item in the listbox, then click the move up button, the item will move up the list, but then the item is no longer highlighted or selected. So, I cannot do consecutive manipulations without reselecting the listbox item.
How can I force my listbox to retain it's selection and highlighting?
Upvotes: 2
Views: 2779
Reputation: 1125
I would bind the ListBox's ItemsSource to an ObservableCollection. Then you can manipulate the ObservableCollection and the ListBox will be updated for you. Here's an example:
The XAML:
<Window x:Class="ListBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ListBox="clr-namespace:ListBox" Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<ListBox:ListBoxViewModel />
</Window.DataContext>
<StackPanel>
<Button Command="{Binding Up}">Up</Button>
<Button Command="{Binding Down}">Down</Button>
<ListBox Grid.Column="0" ItemsSource="{Binding Items}" SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}" />
</StackPanel>
</Window>
and the code:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
namespace ListBox
{
public class ListBoxViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<string> Items {get; private set; }
private void ExecuteUp()
{
if (SelectedIndex == 0)
return;
Items.Move(SelectedIndex, SelectedIndex - 1);
}
private void ExecuteDown()
{
if (SelectedIndex >= Items.Count - 1)
return;
Items.Move(SelectedIndex, SelectedIndex + 1);
}
public ICommand Up { get; private set; }
public ICommand Down { get; private set; }
private int m_SelectedIndex = 0;
public int SelectedIndex
{
get { return m_SelectedIndex; }
set
{
m_SelectedIndex = value;
OnPropertyChanged("SelectedIndex");
}
}
public ListBoxViewModel()
{
Items = new ObservableCollection<string>() {"London", "Paris", "Berlin"};
Up = new RelayCommand(ExecuteUp);
Down = new RelayCommand(ExecuteDown);
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Upvotes: 1
Reputation: 45096
If it is selected but does not have focus by default it loses color
<Style.Resources>
<!-- Background of selected item when focussed -->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Green"/>
<!-- Background of selected item when not focussed -->
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
Color="LightGreen" />
</Style.Resources>
Upvotes: 1