在C#代码中设置listItem文本颜色

时间:2013-01-11 07:58:03

标签: windows-phone-7 listbox windows-phone-7.1 foreground

我有一个listBox,显然通过数据绑定填充了列表项。您可能也知道,您可以使用listItem模板标记指定listItem的外观,如下所示:

<ListBox.ItemTemplate>
    <TextBlock Name="lblName" Text="{Binding Name}" Foreground="black" />
</ListBox.ItemTemplate>

请注意,listItems Textbloxk上的Foreground是黑色的......

现在在我的C#代码中,我想动态地将每个listItems Textblock Foreground设置为我想要的颜色。如何引用特定的listItems Textblock并设置它的前景?

如果需要更多信息,请询问!提前谢谢!

2 个答案:

答案 0 :(得分:2)

你真的需要在代码隐藏中做到这一点吗?

首选解决方案是将Foreground属性绑定到ViewModel的ForegroundColor属性(如果使用MVVM)。

如果您不使用MVVM并且不希望使用Brush属性“污染”您的模型类,则可以将Foreground属性绑定到您班级中已有的属性(例如NameAge)并使用Converter将其设为Brush

<ListBox.ItemTemplate>
    <TextBlock Name="lblName" Text="{Binding Name}" Foreground="{Binding Age, Converter={StaticResource AgeToColorConverter}}" />
</ListBox.ItemTemplate>

转换器的代码:

public class AgeToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Your code that converts the value to a Brush
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

答案 1 :(得分:1)

更好更简单的解决方案是在表示颜色的SolidColorBrush类型的项目中添加属性,让我们调用id ForegroundColor并使用绑定

<ListBox.ItemTemplate>
    <TextBlock Name="lblName" Text="{Binding Name}" Foreground="{Binding ForegroundColor}" />
</ListBox.ItemTemplate>
相关问题