代码之家  ›  专栏  ›  技术社区  ›  tayabuz

如何更改SelectedItem(在列表框中)的颜色?

  •  2
  • tayabuz  · 技术社区  · 7 年前

    下面是一个列表框

    <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问题。答案- List<string> 。需要更改列表框单击处理程序中所选项目的颜色。现在处理程序代码如下所示:

    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的颜色仅在此列表框中更改,有什么必要?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Michael Hawker - MSFT    7 年前

    您正在修改 Application.Current.Resources ,这将影响所有ListView。改为更改控件实例上的资源:

    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 可以拥有自己的资源,在访问父元素(如页面或应用程序)以查找合适的源之前,将首先查看这些资源。