【问题标题】:Is it possible to set a WPF ListBoxItem's background to a hex color stored as a string inside an objects property?是否可以将 WPF ListBoxItem 的背景设置为存储为对象属性内的字符串的十六进制颜色?
【发布时间】:2021-02-18 19:13:37
【问题描述】:

如果我有一个简单的对象,例如:

public class person
{
    string name;
    string color;

    public override string ToString()
    {
        return name;
    }
}

颜色在字符串中被格式化为#FFFFFF。有没有办法在代码后面或 XAML 中将每个单独的项目背景颜色设置为存储在人员对象中的颜色?我将列表框的 itemsource 设置为列表:

ListBox.ItemsSource = listofpeople;

此时我已经尝试遍历 ListBox.items 集合,但这似乎只返回了底层的“人”对象,而不是我想猜测我需要编辑的 ListBoxItem 对象背景属性?这甚至可能在代码后面吗?

【问题讨论】:

    标签: c# wpf wpf-controls


    【解决方案1】:

    你可以有一个合适的 ItemContainerStyle。

    绑定Background="{Binding Color}" 有效,因为有从stringBrush 的内置自动类型转换。

    <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>
    

    Person 类必须声明公共属性:

    public class Person
    {
        public string Name { get; set; }
        public string Color { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 2018-07-24
      相关资源
      最近更新 更多