如何更改 UWP 事件中文本块的背景

How to change background of textblock in an event in UWP

与 WPF 不同,TextBlock 没有背景 属性。 我已经看到解决方法是将文本块包裹在边框中并更改边框的背景。

现在我想在加载文本块时触发的事件中更改边框的背景。

检查触发文本块的父级 属性 我发现它只引用了堆栈面板,但没有引用边框。如何在事件函数中更改边框背景?

我试过的无效代码是这样的:

    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);
        }
    }

XAML代码:

                                         <ListBox.ItemTemplate>
                                                <DataTemplate>
                                                    <Border Background="Gray">
                                                        <StackPanel Orientation="Horizontal">
                                                            <TextBlock x:Name="BitText" Text="{Binding}" Loaded="BitText_Loaded"/>
                                                        </StackPanel>
                                                    </Border>
                                                </DataTemplate>
                                            </ListBox.ItemTemplate>

bitText.Parent 转换为 StackPanel,然后将 StackPanelParent 转换为 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;
    //...
}