C# 是否可以设置WPF ListBoxItem';对象属性中存储为字符串的十六进制颜色的背景?
如果我有一个简单的对象,比如:C# 是否可以设置WPF ListBoxItem';对象属性中存储为字符串的十六进制颜色的背景?,c#,wpf,wpf-controls,C#,Wpf,Wpf Controls,如果我有一个简单的对象,比如: public class person { string name; string color; public override string ToString() { return name; } } 其中颜色的格式为字符串中的#FFFFFF。在code behind或XAML中是否有方法将每个项目的背景颜色设置为person对象中存储的颜色?我正在将列表框的itemsource设置为列表: ListB
public class person
{
string name;
string color;
public override string ToString()
{
return name;
}
}
其中颜色的格式为字符串中的#FFFFFF。在code behind或XAML中是否有方法将每个项目的背景颜色设置为person对象中存储的颜色?我正在将列表框的itemsource设置为列表:
ListBox.ItemsSource = listofpeople;
此时,我已尝试遍历ListBox.items集合,但这似乎只返回底层的“person”对象,而不是我猜需要编辑background属性的ListBoxItem对象?这在代码隐藏中可能吗?您可以使用适当的ItemContainerStyle 绑定
Background=“{Binding Color}”
之所以有效,是因为内置了从string
到Brush
的自动类型转换
<ListBox x:Name="ListBox">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Background" Value="{Binding Color}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public class Person
{
public string Name { get; set; }
public string Color { get; set; }
}