如何改变前景色的文本块是在列表框

本文关键字:文本 列表 前景色 何改变 改变 | 更新日期: 2023-09-27 18:13:43

我有一个列表框和列表框中的文本块,当用户点击文本块时,我想改变文本块的前前景颜色,只有点击的文本块应该改变颜色,例如,如果我点击列表中的另一个文本块,前一个应该有原始颜色

<ListBox Name="URLListBox"  Grid.Row="2"  >
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid Background="Transparent" Margin="0,0,0,10" >
        <Grid.ColumnDefinitions>
          <ColumnDefinition/>
          <ColumnDefinition Width="400"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="1" x:Name="surename" Tag="{Binding b1Tag}" FontFamily="Consolas"  FontSize="25" Text="{Binding text}" Tap="surename_Click_1"  VerticalAlignment="Center" HorizontalAlignment="Center" Margin="60,0,0,0"/>
        <CheckBox IsEnabled="False" BorderThickness="0" BorderBrush="DarkGreen"  Background="DarkGreen"  Grid.Column="0" x:Name="checkbox" IsChecked="{Binding file}"   ></CheckBox>
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

如何改变前景色的文本块是在列表框

您的窗口类可以看起来像:

    public partial class MainWindow : Window
    {
    public MainWindow()
    {
        InitializeComponent();
        foreach (var g in listBox.Items)
        {
            if (g is Grid)
            {
                foreach (var c in (g as Grid).Children)
                {
                    if (c is TextBlock)
                        (c as TextBlock).MouseDown += TextBlock_Click;
                }
            }
        }
    }
    private void TextBlock_Click(object sender, RoutedEventArgs e)
    {
        if (CurrentSelected != null)
            CurrentSelected.Foreground = new SolidColorBrush(Colors.Black); // here you can set foreground default color
        (CurrentSelected = (sender as TextBlock)).Foreground = new SolidColorBrush(Colors.Red); // here you can set foreground after change
    }
    private TextBlock CurrentSelected
    {
        get;
        set;
    }
}

您必须更改列表框的名称。只需添加:

x:Name="listBox"

一个解决方案可能是通过一个额外的属性来扩展你的项目类(因为你已经在使用绑定了):

// in your item class
private SolidColorBrush frontBrush = new SolidColorBrush(Colors.Transparent);
public SolidColorBrush FrontBrush 
{ 
   get { return frontBrush; }
   set { frontBrush = value; RaiseProperty("FrontBrush"); }
}

然后在TextBlock中设置另一个绑定:

<TextBlock Grid.Column="1" x:Name="surename" Foreground="{Binding FrontBrush}" Tag="{Binding b1Tag}" FontFamily="Consolas"  FontSize="25" Text="{Binding text}" Tap="surename_Click_1"  VerticalAlignment="Center" HorizontalAlignment="Center" Margin="60,0,0,0" />

然后你可以简单地改变收集项目的颜色(点击,点击,只要你想):

collection[2].FrontBrush = new SolidColorBrush(Colors.Red);