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

标签 c# xaml uwp uwp-xaml

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

相关文章:

wpf - 如果 ViewModel 中的默认值为 null,则将默认值绑定(bind)到可见性

c# - 0x8007007E 仅在 Windows Phone 目标中

azure - UWP证书构建管道导入错误

c# - 什么是 Rhino Mocks Repeat?

c# - TransactionTimeout 无法正常工作

c# - Task.Factory.StartNew 中的方法(操作)调用未立即调用

uwp - 为什么我的 UWP 应用程序(仅)在 Windows 11 下出现延迟?

c# - 如何在 Deedle 框架中将值从 <string> 转换为 <double> 类型?

c# - 如何将 Datagrid 的 header 绑定(bind)到 View 模型中的值?

c# - MVVM - ListView ItemClick 如何使用 Bindig 执行 RelayCommand