【发布时间】: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,然后将StackPanel的Parent转换为Border? -
是的,谢谢你的工作,我没有注意到我已经将边框也包裹在了堆栈面板周围,这很糟糕
标签: c# uwp background border textblock