在动态绑定的列表中更改单个元素的文本颜色 [英] Changing the text color of individual elements in a dynamically bound list

查看:125
本文介绍了在动态绑定的列表中更改单个元素的文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前正在使用一个Windows Phone(7.5)应用程序,其中一个页面包含绑定到元素列表的列表框。

Currently working on a little Windows Phone (7.5) application and one of the pages contains a ListBox that is bound to a list of elements.

<ListBox x:Name="MyListBox" 
    ItemsSource="{Binding Path=Listing}" 
    ItemTemplate="{StaticResource MyItemTemplate}" />

DataTemplate看起来像下面的Name和Description是类Entity的属性:

The DataTemplate looks like the following where "Name" and "Description" are properties of the class "Entity":

<DataTemplate x:Key="WordTemplate">
    <ListBoxItem Tap="WordTapped">                              
        <StackPanel Orientation="Vertical">
            <TextBlock Width="Auto" 
                     Text="{Binding Name}" 
                     FontSize="{StaticResource PhoneFontSizeLarge}"  
                     VerticalAlignment="Top" 
                     TextWrapping="Wrap"
                     Margin="12, 0, 12, 0" />
            <TextBlock Width="Auto" 
                     Text="{Binding Description}" 
                     Style="{StaticResource PhoneTextSmallStyle}" 
                     VerticalAlignment="Top"
                     TextWrapping="Wrap"                                         
                     Margin="12, 0, 12, 12" />              
        </StackPanel>
    </ListBoxItem>
</DataTemplate> 

可以根据Name / Description的实际值更改每个TextBlock?

Is it possible - depending on the actual value of Name/Description - to change the font color of each TextBlock?

推荐答案

是的,使用 ValueConverter 对刷子的描述:

Yes, use a ValueConverter that converts your Name and Description to a brush:

    <phone:PhoneApplicationPage.Resources>
        <Converters:TextToBrushConverter x:Key="yourConverter"/>
    </phone:PhoneApplicationPage.Resources>

    ...
    <TextBlock Width="Auto" 
          Text="{Binding Name}" 
          ...
          Foreground={Binding Name, Converter={StaticResource yourConverter}} />

转换器:

public class TextToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((string)value == "XXX")
        {
            return new SolidColorBrush(Colors.Red);
        }

        return new SolidColorBrush(Colors.Green);
    }

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

这篇关于在动态绑定的列表中更改单个元素的文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆