简体   繁体   中英

How to change background of textblock in an event in UWP

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>

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;
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM