每个列表框项目上的不同背景

时间:2014-04-12 07:40:41

标签: c# wpf windows-phone-8 listbox

我的表格中包含一个包含项目绑定的列表框,其中包含5列(idStory,title,created,textStory和feeling)。

<ListBox x:Name="MainListBox" Height="418" SelectionChanged="MainListBox_SelectionChanged">
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel x:Name="listPanel" Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0,5,0,0">
            <Rectangle Width="100" Height="100" Fill="#e34d64" />
            <StackPanel Orientation="Vertical" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="15,0,0,0">
                <TextBlock Text="{Binding Title}" FontSize="26" Foreground="Black"/>
                <TextBlock Text="{Binding Created}" FontSize="20" Foreground="Black"/>
                <TextBlock Text="{Binding TextStory}" FontSize="20" Foreground="Black" FontStyle="Italic"/>
            </StackPanel>
            <toolkit:ContextMenuService.ContextMenu>
                <toolkit:ContextMenu>
                    <toolkit:MenuItem x:Name="menuEdit" Header="Edit Story" Click="menuEdit_Click"/>
                    <toolkit:MenuItem x:Name="menuDelete" Header="Delete Story" Click="menuDelete_Click"/>
                </toolkit:ContextMenu>
            </toolkit:ContextMenuService.ContextMenu>
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

效果很好,但我想改变每个项目的背景取决于列的感觉。例如,如果我们得到字符串“sad”,那么列表框项目将为蓝色作为背景,如http://imgur.com/n5LoNgj

我应该怎么做才能让它真实?任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:2)

为了您的目的,我建议使用转换器将TextBox的背景(或者更好的整个StackPanel - 您的选择)绑定到Feeling属性:

<TextBlock Text="{Binding Title}" FontSize="26" Foreground="Black" Background={Binding Feeling, Converter={StaticResource TxtToBrush}}/>

您必须在参考资料中的某处添加密钥:

xmlns:conv="clr-namespace:Yournamespace"
<conv:TextToBrush x:Key="TxtToBrush"/>

转换器看起来像这样:

public class TextToBrush : IValueConverter
{
    List<Tuple<string, Brush>> textBrush = new List<Tuple<string, Brush>>()
    {
        new Tuple<string, Brush>("sad", new SolidColorBrush(Colors.Blue))
    };

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return new SolidColorBrush(Colors.Transparent);
        else
        {
            foreach (Tuple<string,Brush> item in textBrush)
                if ((value as string) == item.Item1) return item.Item2 as Brush;
        }
        return new SolidColorBrush(Colors.Transparent);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

当然,您的财产BGColor应该提出OnPropertyChanged(您的项目类应该强制INotifyPropertyChanged)。