【问题标题】:How to change background of textblock in an event in UWP如何在 UWP 中的事件中更改文本块的背景
【发布时间】:2019-06-26 13:14:20
【问题描述】:

与 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>

【问题讨论】:

  • 您是否尝试先将bitText.Parent 转换为StackPanel,然后将StackPanelParent 转换为Border
  • 是的,谢谢你的工作,我没有注意到我已经将边框也包裹在了堆栈面板周围,这很糟糕

标签: c# uwp background border textblock


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-11-08
    • 2017-12-29
    • 1970-01-01
    • 2018-06-19
    • 2020-12-03
    • 1970-01-01
    • 2019-12-22
    • 2016-07-26
    • 1970-01-01
    相关资源
    最近更新 更多