c# - 有没有办法覆盖列表框中所有项目的颜色?

标签 c# wpf xaml data-binding

我正在使用 WPF 进行 GUI 设计,并且我的 GUI 包含一个列表框。简而言之,我试图使列表框的所有项目具有相同的前景色#FF548E19。据我所知,输入列表框中的每个单独项目的前景色可以由 XAML 属性定义:

Foreground="#FF548E19"

由于我实际上是在我构建的 View 模型中使用数据绑定(bind),所以我不能简单地为每个项目设置 Foreground 属性,因为它们是在运行时填充的 -时间。作为替代方案,我尝试在列表框本身上设置 Foreground 属性。这没有任何作用,所有项目仍然以白色颜色显示。

问题

有没有办法确保每个绑定(bind)项(填充到列表框中的项)获得前景色#FF548E19,而无需在运行时手动更改颜色?

更新

其中一条评论询问我实际上如何用项目填充列表框。因此,这是在属性更改时被插入列表框的数据绑定(bind)属性。

/// <summary>
/// A list of the failure codes (per entry).
/// </summary>
public List<string> FailCodes
{
    get
    {
        return this.failCodes;
    }

    set
    {
        this.failCodes = value;
        this.OnPropertyChanged("FailCodes");
    }
}

此外,这是 XAML 属性(包括 ItemsSource 如何绑定(bind))。

<ListBox x:Name="listBox_failCodes"
         Grid.Row="0" 
         Margin="0" Background="{x:Null}" 
         HorizontalContentAlignment="Center"
         BorderBrush="{x:Null}" 
         Foreground="#FF548E19" 
         ItemsSource="{Binding FailCodes}"/>

最佳答案

在您的标记中,使用 item template (如 suggested in the comments )具有静态 Foreground 值:

<ListBox x:Name="listBox_failCodes"
     Grid.Row="0" 
     Margin="0" Background="{x:Null}" 
     HorizontalContentAlignment="Center"
     BorderBrush="{x:Null}" 
     ItemsSource="{Binding FailCodes}"/>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Foreground="#FF548E19" Text="{Binding}"></TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这将应用于绑定(bind)到列表框的每个项目

关于c# - 有没有办法覆盖列表框中所有项目的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40728760/

相关文章:

c# - XAML 数据类型中的神秘 `1

c# - 如何将Appium与C#集成?

wpf - 将文字附加到静态资源

c# - 调整 WPF ListBox 选择框的大小

c# - 如何生成随机值以在 wpf 中绘制条形图?

c# - 本地化绑定(bind)

c++ - 有什么方法可以在 x < 8 的 Windows x 上从 native C++ 应用程序使用 XAML 和 WPF?

c# - DataGridViewColumn EditingControl 编辑值未反射(reflect)

c# - StreamReader 行和行分隔符

c# - 如何在提供 IQueryable 输出的 linq 查询中使用 Func