数据触发器在条件下改变listboxitem的背景颜色

本文关键字:背景 颜色 listboxitem 改变 触发器 条件下 数据 | 更新日期: 2023-09-27 18:06:58

我想改变一个listboxitem的背景颜色,当一行在SQLite数据库是1

我的代码是这样的

public void getMailsFromDb()
    {
        string myConnString = "Data Source=db.s3db;Version=3;";
        string mySelectQuery = "SELECT * FROM `emails` ORDER BY `date` DESC, `time` DESC";
        SQLiteConnection sqConnection = new SQLiteConnection(myConnString);
        SQLiteCommand sqCommand = new SQLiteCommand(mySelectQuery, sqConnection);
        sqConnection.Open();
        try
        {
            SQLiteDataReader sqReader = sqCommand.ExecuteReader();
            while (sqReader.Read())
            {
                string from = sqReader.GetString(sqReader.GetOrdinal("sender"));
                string subject = sqReader.GetString(sqReader.GetOrdinal("subject"));
                string msgid = sqReader.GetString(sqReader.GetOrdinal("messageId"));            
                App.Current.Dispatcher.Invoke((Action)delegate
                {
                    ListBoxData.Add(new EmailEntry { from = from, subject = subject, messageID = msgid });
                    // HERE IS THE PLACE WHERE I WANT TO CHANGE THE BG COLOUR OF THE LISTBOX ITEM
                });
            }
            sqReader.Close();
        }
        catch
        {
            MessageBox.Show("Problems reading mails from database!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }
        finally
        {
            sqConnection.Close();
        }

我认为应该使用Data触发器。然而,我不知道如何使用它。我是WPF的新手。这是我的ListBox XAML

<ListBox Name="EmailList" ItemsSource="{Binding ListBoxData, Mode=TwoWay}" HorizontalContentAlignment="Stretch" Margin="10" SelectionChanged="EmailEntry_SelectionChanged">
                       <ListBox.ItemContainerStyle>
                        <Style TargetType="{x:Type ListBoxItem}">
                            <Setter Property="FocusVisualStyle" Value="{x:Null}" />
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="ListBoxItem">
                                        <Border BorderBrush="#000000" BorderThickness="0 0 0 1" Name="Border" Margin="0" Padding="0" SnapsToDevicePixels="true">
                                            <ContentPresenter />
                                        </Border>
                                        <ControlTemplate.Triggers>
                                            <Trigger Property="IsSelected" Value="true">
                                                <Setter TargetName="Border" Property="Background" Value="#dcdcdc" />
                                            </Trigger>
                                            <Trigger Property="IsMouseOver" Value="true">
                                                <Setter TargetName="Border" Property="Background" Value="#f0f0f0"></Setter>                         
                                            </Trigger>
                                        </ControlTemplate.Triggers>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </ListBox.ItemContainerStyle>
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel HorizontalAlignment="Stretch" Tag="{Binding messageID}">
                                <TextBlock Name="fromTxt" Text="{Binding from}" HorizontalAlignment="Stretch"/>
                                <TextBlock Name="subjectTxt" Text="{Binding subject}" HorizontalAlignment="Stretch"/>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

我得到了正常的触发器工作,鼠标悬停等。但是我对数据触发部分感到困惑,什么时候在代码中使用,我相信它被称为。有人能帮忙吗?

数据触发器在条件下改变listboxitem的背景颜色

您可以使用IValueConverter。

参考下面我将List绑定到ListBox的代码。我想要我的ListBoxItem有一个浅绿色的背景奇数和浅蓝色的偶数。

public partial class MainWindow : Window
    {
        public List<int> ListBoxData { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            ListBoxData = new List<int>() { 1, 2, 3, 4, 5, 6 };
            DataContext = this;
        }
    }
    public class NumberToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            int number = (int)value;
            if (number % 2 == 0)
            {
                return Brushes.LightBlue;
            }
            return Brushes.LightGreen;
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication3"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox ItemsSource="{Binding ListBoxData}">
            <ListBox.Resources>
                <local:NumberToColorConverter x:Key="NumberToColorConverter"/>
                <Style TargetType="ListBoxItem">
                    <Setter Property="Background" Value="{Binding Converter={StaticResource NumberToColorConverter}}"/>
                </Style>
            </ListBox.Resources>
        </ListBox>
    </Grid>
</Window>

正如您提到的,您是WPF的新手,这个链接可以帮助您理解值转换器