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

时间:2014-06-04 19:55:00

标签: c# wpf datatrigger listboxitem

我希望在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>

我得到了正常的触发器,鼠标悬停等等。但我很困惑数据触发器部分什么时候在代码背后使用我相信它被称为。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

相反,您可以使用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新手,这个link可以帮助您理解价值转换器