1

我有一个列表框,它绑定到一个字符串数组。列表框包含一个文本块,其中包含数组中字符串的文本。我想改变其中之一的前景(可能会有所不同):

 <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>

我似乎无法掌握文本块,所以我可以更改右侧的前景。有谁知道我怎么能做到这一点?谢谢

4

1 回答 1

2

将 Foreground 属性绑定到与 Text 相同的值,并使用 BindingConverter 从中创建一个 Brush。例如

<Grid.Resources>
  <yournamespace:ColorConverter x:Key="colConverter"/>
<Grid.Resources>


<TextBlock 
  HorizontalAlignment="Center"
  Text="{Binding}"
  Foreground="{Binding, Converter={StaticResource colConverter}}"
  Style="{StaticResource SortingOptions}" />

添加您的转换器类:

  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();
  }
}
于 2012-07-25T12:33:49.917 回答