繁体   English   中英

C#WPF-数据触发器可根据条件更改listboxitem中的背景颜色

[英]C# WPF - Data trigger to change background color in listboxitem on condition

我想在SQLite DB中的一行为1时更改listboxitem的背景颜色

我的代码看起来像这样

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();
        }

我认为应该使用的是数据触发器。 但是我不确定如何使用它。 我是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>

我使正常的触发器工作了,例如鼠标悬停等等。 但是我对数据触发器部分感到困惑,我认为它何时会在后面的代码中使用。 有人可以协助吗?

相反,您可以使用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的新手,此链接可以帮助您了解值转换器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM