WPF 后台设置 Background
时间: 2024-01-21 14:04:35 浏览: 36
在 WPF 中,可以通过以下方式设置后台颜色:
1. 在 XAML 中设置 Background 属性:
```
<Grid Background="LightGray">
<!-- 内容 -->
</Grid>
```
2. 在代码中设置 Background 属性:
```
grid.Background = Brushes.LightGray;
```
其中,grid 是一个 WPF 控件。Brushes 是一个静态类,提供了许多预定义的画刷,可以用于设置颜色。在这个例子中,使用了 LightGray 画刷来设置背景颜色。
相关问题
WPF 后台设置背景色
在WPF中,可以通过在后台代码中设置Brush对象来设置背景色。以下是一个示例:
```csharp
// 创建一个红色的Brush对象
SolidColorBrush redBrush = new SolidColorBrush(Colors.Red);
// 将背景色设置为红色
this.Background = redBrush;
```
你可以将上述代码放在WPF窗口或控件的构造函数中,以设置其背景色为红色。你也可以使用其他类型的Brush对象来设置不同的背景效果,比如渐变色或图像纹理等。
WPF中后台定义FormattedText
在 WPF 中,可以使用 FormattedText 类在后台代码中定义并格式化文本,然后将其绘制在画布或其他控件上。以下是在后台代码中声明 FormattedText 的示例:
```csharp
// 创建一个新的FormattedText对象
FormattedText formattedText = new FormattedText(
"Hello World",
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface("Arial"),
20,
Brushes.Red,
VisualTreeHelper.GetDpi(this).PixelsPerDip);
// 设置文本的对齐方式
formattedText.TextAlignment = TextAlignment.Center;
// 设置文本的背景色
formattedText.SetBackgroundBrush(Brushes.Yellow);
// 在画布上绘制文本
Canvas canvas = new Canvas();
TextBlock textBlock = new TextBlock();
textBlock.FontFamily = new FontFamily("Arial");
textBlock.FontSize = 20;
textBlock.Foreground = Brushes.Red;
textBlock.Background = Brushes.Yellow;
textBlock.Text = formattedText.Text;
// 将 TextBlock 添加到画布中
Canvas.SetLeft(textBlock, 10);
Canvas.SetTop(textBlock, 10);
canvas.Children.Add(textBlock);
```
在这个示例中,我们首先创建一个新的 FormattedText 对象,设置文本、语言环境、文本流动方向、字体类型、字体大小、前景色和 DPI 值。然后,我们可以使用 SetBackgroundBrush 方法设置文本的背景色,并使用 TextAlignment 属性设置对齐方式。
最后,我们在 Canvas 上创建一个 TextBlock 控件,并将其添加到画布中。我们可以设置 TextBlock 的属性,如 FontFamily、FontSize、Foreground 和 Background,以匹配我们在 FormattedText 中设置的样式。然后,我们将 formattedText.Text 赋值给 TextBlock 的 Text 属性,以便在 TextBlock 中显示文本。最后,我们使用 Canvas.SetLeft 和 Canvas.SetTop 方法将 TextBlock 放置在画布上。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)