WP7:根据另一个Textblock的值更改Textblock Foreground颜色

时间:2010-12-18 21:25:47

标签: c# xaml windows-phone-7

说我有这个XAML:

<TextBlock Name="t1" Text="{Binding team1}" Foreground="White"  FontSize="32"   />
<ListBox Name="lbBooks" Width="441" Height="490" >
    <ListBox.ItemTemplate>
        <DataTemplate x:Name="d1" >
        <StackPanel Name="spMain">      
            <StackPanel Orientation="Horizontal" >                          
            <HyperlinkButton Content="{Binding BookName}" Margin="5" Width="230" TargetName="_blank" NavigateUri="{Binding BookWebsite}"/>

            <StackPanel Orientation="Vertical" HorizontalAlignment="Right" Margin="0,0,0,0" >
                <TextBlock Name="b1" Text="{Binding BookLine1}" Margin="5" Width="160" HorizontalAlignment="Right"></TextBlock>
                <TextBlock Name="b1U" Text="{Binding BookLine2}" Margin="5" Width="160" Foreground="Wheat" HorizontalAlignment="Right"></TextBlock>
                <TextBlock Name="b3" Text="{Binding BookLine3}" Margin="5" Width="160" DataContext="{Binding team1,Converter={StaticResource tbConverter}, ElementName=b3, Mode=TwoWay}"   HorizontalAlignment="Right"></TextBlock>
            </StackPanel>
        </StackPanel>       
        </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我想根据TextBlock“t1”的值更改名为“b3”的TextBlock的前景色。我知道我需要实现类似下面的转换器:

public class TBConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //do I need to check against the Textblock t1 value in here?
            if (value != null && t1.Text == "Text that triggers change" ) 
            {
             //need code to change Textblock foreground color  
            }
            return null;
        }

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

那么,(1)转换器中需要的代码是什么来改变Textblock b3的前景色? (2),我是否在Textblock“b3”的datacontext中正确调用了转换器? 谢谢!

1 个答案:

答案 0 :(得分:2)

如果您的文本块b1已绑定到变量(此处为team1),您还可以使用转换器将t3的Foreground绑定到它:

Foreground="{Binding team1, Converter={StaticResource YourConverter}}"

并且在您的转换器中,tema1的值将作为值(对象)传递:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)              
{                  
   var team1 = valus as YourType
   if(team1 == xxx)
   {
     return newColorBrush;

   }else{

     return defaultColorBrush; //maybe from your styles etc...

   }

}