我有一个列表框,它已经绑定了一个字符串数组。列表框包含一个文本块,其中包含数组中字符串的文本。我想改变其中一个的前景(它可能会改变哪一个):
<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>
我似乎无法抓住文本块,所以我可以改变右边的前景。有谁知道我怎么能做到这一点?感谢
答案 0 :(得分:2)
将Foreground属性绑定到与Text相同的值,并使用BindingConverter创建一个Brush。 E.g。
<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();
}
}