Reputation: 29
Unlike WPF, TextBlock has no background property. I've seen that a workaround for that would be wrapping the textblock in a border and changing the border's background.
Now I want to change the border's background in an event triggered when the textblock is loaded.
checking the Parent property of the triggered textblock I see it only has a reference to the stackpanel but not the border. How can I change the borders background in the event function?
the not working code i've tried is this:
private void BitText_Loaded(object sender, RoutedEventArgs e)
{
TextBlock bitText = sender as TextBlock;
Border border = bitText.Parent as Border;
if ((int)bitText.DataContext == 1)
{
bitText.Foreground = new SolidColorBrush(Windows.UI.Colors.LightGreen);
border.Background = new SolidColorBrush(Windows.UI.Colors.DarkGreen);
}
else
{
bitText.Foreground = new SolidColorBrush(Windows.UI.Colors.Gray);
border.Background = new SolidColorBrush(Windows.UI.Colors.LightGray);
}
}
The XAML Code:
<ListBox.ItemTemplate>
<DataTemplate>
<Border Background="Gray">
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="BitText" Text="{Binding}" Loaded="BitText_Loaded"/>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
Upvotes: 1
Views: 239
Reputation: 169210
Cast bitText.Parent
to a StackPanel
and then cast the Parent
of the StackPanel
to a Border
:
private void BitText_Loaded(object sender, RoutedEventArgs e)
{
TextBlock bitText = sender as TextBlock;
StackPanel stackPanel = bitText.Parent as StackPanel;
Border border = stackPanel.Parent as Border;
//...
}
Upvotes: 1