[英]how to change foreground color of textblock which is under listbox
i have a list box and text block in list-box .I want to change foreground color of text-block when user tap text-block , only tapped text-block should change color for example if i tap another text-block in list previous one should have original color 我在列表框中有一个列表框和文本块。我想在用户点击文本块时更改文本块的前景色,例如,如果我在列表中的前一个文本框中点按了另一个文本块,则只有轻敲的文本块才应更改颜色一个应该具有原始颜色
<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>
Your window class can look like: 您的窗口类如下所示:
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;
}
}
And you have to chnage name of your list box. 并且您必须更改列表框的名称。 Simply add:
只需添加:
x:Name="listBox"
to your list box declaration in XAML. 到XAML中的列表框声明。
One solution may be to extend your item class by an additional property (as you are already using binding): 一种解决方案可能是通过附加属性扩展您的商品类(因为您已经在使用绑定):
// in your item class
private SolidColorBrush frontBrush = new SolidColorBrush(Colors.Transparent);
public SolidColorBrush FrontBrush
{
get { return frontBrush; }
set { frontBrush = value; RaiseProperty("FrontBrush"); }
}
Then you just set another binding in your TextBlock: 然后,您只需在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" />
Then you can simply change colors of your items in a collection (upon click, tap, whenever you want): 然后,您可以简单地更改集合中项目的颜色(单击,随时点击)。
collection[2].FrontBrush = new SolidColorBrush(Colors.Red);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.