每个列表框项目的不同背景
Posted
技术标签:
【中文标题】每个列表框项目的不同背景【英文标题】:Different background on each Listbox item 【发布时间】:2021-05-29 09:14:33 【问题描述】:我的表上有一个包含项目绑定的列表框,它由 5 列(idStory、title、created、textStory 和 feel)组成。
<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
我应该怎么做才能使它成为现实?任何帮助将不胜感激。谢谢。
【问题讨论】:
我从问题的标题中删除了一个标签。请注意,在大多数情况下,问题shouldn't include tags in their title. 哦,我很抱歉。谢谢 @Romaz 标签在标题中很好,如果它们以流畅的方式集成在这个问题中(参见链接中的第二个示例)。 【参考方案1】:出于您的目的,我建议将您的 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
)。
【讨论】:
嘿,谢谢。我做了转换器,看起来更好。但现在我尝试将图像设置为我的背景。如果我将我的堆栈面板属性设置为 ImageSource="Binding some_url_of_my_asset" 是否有可能? @SonicMaster StackPanel 没有属性 ImageSource。你当然可以绑定你的 Image 的 ImageSource (你会在 SO 上找到很多答案)。如果您想将图像设置为背景,您可能对ImageBrush class 感兴趣。您可以创建 getter 将返回的另一个属性,例如 imagebrush。 @SonicMaster 欢迎您。请记住,如果其中一个答案解决了您的问题,请不要忘记accept it。以上是关于每个列表框项目的不同背景的主要内容,如果未能解决你的问题,请参考以下文章