c# - 如何在 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>
解决方案
转换bitText.Parent
为 aStackPanel
然后将Parent
theStackPanel
转换为 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;
//...
}
推荐阅读
- javascript - ShellJs 执行 CLI 命令
- java - 复制在模拟器上工作但在安卓设备上不工作的音频文件
- python - 在python中用lambda替换嵌套的'for循环'
- matlab - 如何在matlab中连接单词/短语
- video-streaming - 如果上传的文件是 *.avi 或 *.flv 类型,如何在 JavaScript 中获取 *.avi *.flv、*.rmvb 文件的持续时间?
- python - 双标量中遇到溢出错误
- c# - C# 在 MaskedTextBox 中显示 /(正斜杠)
- python - 用来自另一个数据框值的值填充熊猫数据框行中的特定列
- nltk - 在 nltk 中,如何将过去分词动词转换为基本形式?
- android-studio - Android Studio 没有在 Theme 中显示任何已安装的插件