2010-12-18 31 views
0

說我有這樣的XAML:WP7:基於另一個文本塊的值更改文本塊前景色

<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的前景色「B3」根據TextBlock的「T1」的價值。我知道我需要實現一個轉換器有點像下面這樣:

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)什麼是我需要在轉換器的代碼更改文本塊B3的前景色? 和(2),我是否正確調用了文本塊「b3」的datacontext中的轉換器? 謝謝!

回答

2

如果你的文本塊B1已經綁定到一個變量(這裏TEAM1),你也可以綁定T3的前景將其與轉換器:

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

,並在轉換器tema1的價值將被傳遞作爲值(oject):

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

    } 

}  
+0

非常感謝您的幫助!我必須使綁定如下所示: Foreground =「{Binding ElementName = t1,Converter = {StaticResource TBConverter}}」 – sleeprince 2010-12-19 22:40:59

+0

公共對象轉換(對象值, 類型targetType, 對象參數, System.Globalization.CultureInfo文化) { var league = value as TextBlock; (League.Text.Contains(「Chicago」)) { }返回新的SolidColorBrush(Colors.Brown);如果(League!= null) } } 返回新的SolidColorBrush(Colors.White); ; } – sleeprince 2010-12-19 22:45:08

相關問題