gpt4 book ai didi

c# - 如何更改 SelectedItem(在 ListBox 中)的颜色?

转载 作者:太空宇宙 更新时间:2023-11-03 12:15:33 25 4
gpt4 key购买 nike

有如下的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>

哪里有问题。答案 - 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 中发生了变化?

最佳答案

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

关于c# - 如何更改 SelectedItem(在 ListBox 中)的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49927392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com