我在列表框中有一个列表框和文本块。我想在用户点击文本块时更改文本块的前景色,只有点击的文本块应该更改颜色,例如,如果我点击另一个文本块在列表中,前一个应该有原始颜色
<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>
答案 0 :(得分:0)
您的窗口类看起来像:
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"
到XAML中的列表框声明。
答案 1 :(得分:0)
一种解决方案可能是通过附加属性扩展您的item类(因为您已经在使用绑定):
// 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);