locked
ListBox item - is it possible to change Foreground of selected item? RRS feed

  • Question

  • Hi I have textblock in data template to display text of the item, I have ListBoxItem template where I have Selected visual state and ContentPresenter which presents an item.

    How can I change foreground colour of the textblock in Selected state?

    Sunday, March 29, 2009 6:11 PM

Answers

  • Hi,

    You could use the SelectionChanged event like I have done in this example:
    <ListBox x:Name="myListBox" SelectionChanged="ListBox_SelectionChanged">
        <ListBoxItem Content="Item 1" />
        <ListBoxItem Content="Item 2" />
        <ListBoxItem Content="Item 3" />
        <ListBoxItem Content="Item 4" />
    </ListBox>

    and in the C#:

    public partial class MainPage : UserControl
    {
        private int previousIndex = -1;
    
        public MainPage()
        {
            InitializeComponent();
        }
    
        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (previousIndex >= 0)
            {
                ((ListBoxItem)myListBox.Items[previousIndex]).Foreground = new SolidColorBrush(Colors.Black);
            }
    
            ((ListBoxItem)myListBox.SelectedItem).Foreground = new SolidColorBrush(Colors.Red);
    
            previousIndex = myListBox.SelectedIndex;
        }
    }

    Hope this helps!

    Sunday, March 29, 2009 7:04 PM