有以下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>
Question.Answers - List<string>
。有必要在ListBox单击处理程序中更改所选项的颜色。现在处理程序代码如下所示:
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);
}
}
此方法存在的问题是应用程序中的颜色会发生变化。 SelectedItem的颜色仅在此ListBox中发生了什么变化?
答案 0 :(得分:1)
您正在修改Application.Current.Resources
,这将影响所有列表视图。而是改变控件实例上的资源:
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);
}
}
每个FrameworkElement
都可以拥有自己的资源,在走向父元素(如网页或应用)之前先查看这些资源,以寻找合适的资源。