簡體   English   中英

是否可以將 WPF ListBoxItem 的背景設置為存儲為對象屬性內的字符串的十六進制顏色?

[英]Is it possible to set a WPF ListBoxItem's background to a hex color stored as a string inside an objects property?

如果我有一個簡單的 object ,例如:

public class person
{
    string name;
    string color;

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

顏色在字符串中被格式化為#FFFFFF。 有沒有辦法在代碼后面或 XAML 中將每個單獨的項目背景顏色設置為存儲在人員 object 中的顏色? 我將列表框的 itemsource 設置為列表:

ListBox.ItemsSource = listofpeople;

此時我已經嘗試遍歷 ListBox.items 集合,但這似乎只返回底層的“人”對象,而不是我猜想我需要編輯背景屬性的 ListBoxItem 對象? 這甚至可能在后面的代碼中嗎?

你可以有一個合適的 ItemContainerStyle。

Binding 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 class 必須聲明公共屬性:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM