首页 > 解决方案 > 如何在 UWP 中的事件中更改文本块的背景

问题描述

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

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

检查触发的文本块的 Parent 属性,我发现它只有对堆栈面板的引用,而不是对边框的引用。如何更改事件函数中的边框背景?

我试过的不工作的代码是这样的:

    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>

标签: c#uwpbackgroundbordertextblock

解决方案


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

推荐阅读