Search code examples
windows-phone-7data-bindinglistboxtextblockforeground

Setting foreground of one specific textblockelement in a listbox - wp7


I've got a listbox, which ive bound to an array of strings. The listbox contains a textblock, which has the text of a string in the array. I want to change the foreground of one of those (it may vary which one):

 <ListBox x:Name="listBox" ItemsSource="{Binding Options}" ScrollViewer.VerticalScrollBarVisibility="Hidden" Width="400" Height="500" Margin="0,200,0,0" HorizontalAlignment="Center" HorizontalContentAlignment="Center" SelectionChanged="ListBox_SelectionChanged" Loaded="listBox_Loaded">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ListBoxItem>
                        <Grid Height="75" Width="400" HorizontalAlignment="Center" >
                            <TextBlock HorizontalAlignment="Center" Text="{Binding}" Style="{StaticResource SortingOptions}" />
                        </Grid>
                    </ListBoxItem>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

I just cant seem to get hold of the textblocks, so i can change the foreground on the right one. Does anyone know how i can achieve this? Thanks


Solution

  • Bind the Foreground property to the same value as Text and use a BindingConverter to create a Brush out of it. E.g.

    <Grid.Resources>
      <yournamespace:ColorConverter x:Key="colConverter"/>
    <Grid.Resources>
    
    
    <TextBlock 
      HorizontalAlignment="Center"
      Text="{Binding}"
      Foreground="{Binding, Converter={StaticResource colConverter}}"
      Style="{StaticResource SortingOptions}" />
    

    Add your converter class:

      public class ColorConverter : IValueConverter
      {
      public object  Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
          // TODO: match from the value parameter to a color.
    
          return new SolidColorBrush(Colors.Red);
      }
    
      public object  ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
          throw new NotImplementedException();
      }
    }