如何更改列表框中项目的字体颜色(wpf)

时间:2011-05-07 07:39:01

标签: wpf colors listboxitem

我有一个列表框,它与可观察的集合有关。集合中的元素包含一个名为color的变量。我的列表框的项目已经绑定到集合,但是如何将项目字体颜色绑定到该集合?我已经有了一个数据模板,可以正常使用颜色名称替换项目的名称,如此

<DataTemplate x:Key="myListBox">
        <TextBlock Padding="0,0,10,0" 
    Text="{Binding Path=Color, Mode=Default}"/>
    </DataTemplate>

但我似乎无法找到为了绑定颜色而必须设置的属性。

2 个答案:

答案 0 :(得分:2)

不确定您所指的是哪种颜色,但这会设置背景和文字/前景色。

<TextBlock Padding="0,0,10,0" 
    Text="{Binding Path=Color, Mode=Default}"
    Background="{Binding myBackgroundColour}"
    Foreground="{Binding myTextColour}"
/>

编辑:依赖性支柱 -

public string Color
{
    get { return (string)GetValue(ColorProperty); }
    set { SetValue(ColorProperty, value); }
}

// Using a DependencyProperty as the backing store for Color.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty ColorProperty =
    DependencyProperty.Register("Color", typeof(string), typeof(CLASSNAMEHERE), new UIPropertyMetadata("Black"));

将CLASSNAMEHERE替换为您要放入的类的名称,即viewmodel类或codebehind类名。

使用:

this.Color = "Yellow";

答案 1 :(得分:1)

您可以使用此资源样式

    <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="Foreground" Value="></Setter>
        <Setter Property="FontWeight" Value="Bold"></Setter>
        bla bla bla
    </Style>
相关问题