Reputation: 25
There is the following ListBox
<ListBox x: Name = "ListBoxQuestionAnswers" ItemsSource = "{x: Bind Question.Answers}" SelectionMode = "Single" SelectionChanged = "ListBoxQuestionAnswers_OnSelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock x: Name = "TextBlockInListBox" TextWrapping = "Wrap" Text = "{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Where Question.Answers - List<string>
. It is necessary to change the color of the selected item in the ListBox click handler. Now the handler code looks like this:
private void ListBoxQuestionAnswers_OnSelectionChanged (object sender, SelectionChangedEventArgs e)
{
if (ListBoxQuestionAnswers.SelectedIndex == Question.CorrectAnswerIndex)
{
Application.Current.Resources ["SystemControlHighlightListAccentLowBrush"] = new SolidColorBrush (Colors.Green);
Application.Current.Resources ["SystemControlHighlightListAccentMediumBrush"] = new SolidColorBrush (Colors.Green);
}
else
{
Application.Current.Resources ["SystemControlHighlightListAccentLowBrush"] = new SolidColorBrush (Colors.Red);
Application.Current.Resources ["SystemControlHighlightListAccentMediumBrush"] = new SolidColorBrush (Colors.Red);
}
}
The problem with this method is that the color changes everywhere in the app. What is necessary that SelectedItem's color has changed only in this ListBox?
Upvotes: 2
Views: 305
Reputation: 1580
You're modifying the Application.Current.Resources
, which will effect all listviews. Instead change the resources on your control instance instead:
private void ListBoxQuestionAnswers_OnSelectionChanged (object sender, SelectionChangedEventArgs e)
{
if (ListBoxQuestionAnswers.SelectedIndex == Question.CorrectAnswerIndex)
{
ListBoxQuestionAnswers.Resources ["SystemControlHighlightListAccentLowBrush"] = new SolidColorBrush (Colors.Green);
ListBoxQuestionAnswers.Resources ["SystemControlHighlightListAccentMediumBrush"] = new SolidColorBrush (Colors.Green);
}
else
{
ListBoxQuestionAnswers.Resources ["SystemControlHighlightListAccentLowBrush"] = new SolidColorBrush (Colors.Red);
ListBoxQuestionAnswers.Resources ["SystemControlHighlightListAccentMediumBrush"] = new SolidColorBrush (Colors.Red);
}
}
Every FrameworkElement
can have its own resources which will be looked at first before walking up to parent elements (like pages or the app) to look for a suitable source.
Upvotes: 1