后台用代码设置color

纯色:

SolidColorBrush brush = new SolidColorBrush(Colors.White);
window1.Background = brush;

渐变色:

LinearGradientBrush buttonBrush = new LinearGradientBrush(); 
buttonBrush.StartPoint = new Point(0, 0.5); 
buttonBrush.EndPoint = new Point(1, 0.5); 
buttonBrush.GradientStops.Add(new GradientStop(Colors.Green, 0)); 
buttonBrush.GradientStops.Add(new GradientStop(Colors.White, 0.9)); 

图片:

textBlock1.Background = new ImageBrush(new BitmapImage(new Uri(@"../Image/Bg.png", UriKind.RelativeOrAbsolute)));

如何将图片 设置为窗体的背景:

System.Drawing.Bitmap bitmap = global::WpfApplication1.Properties.Resources.bg;
ImageSourceConverter convert = new ImageSourceConverter();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
ImageBrush b = new ImageBrush();
b.ImageSource = (ImageSource)convert.ConvertFrom(ms);
this.Background = b; 

转载自:http://www.verydemo.com/demo_c134_i25143.html

### 如何在WPF后台代码设置颜色 在 Windows Presentation Foundation (WPF) 应用程序中,可以通过多种方式在后台代码(Code-Behind)中设置控件的颜色属性。以下是几种常见方法: #### 方法一:直接设置 Brush 属性 可以直接为控件的背景或前景色等属性分配 `SolidColorBrush` 对象。 ```csharp button.Background = new SolidColorBrush(Colors.Red); ``` 此代码片段展示了如何将按钮的背景色设为红色[^1]。 #### 方法二:使用静态资源定义颜色并引用 如果希望在整个应用程序范围内重用某种特定颜色,则可以先在 XAML 文件中的 `<Window.Resources>` 或者 App.xaml 中声明该颜色作为静态资源,之后再于 Code-Behind 中获取这个资源来应用到不同元素上。 XAML 定义部分如下所示: ```xml <Window.Resources> <Color x:Key="MyCustomColor">#FF00FF</Color> <!-- Magenta --> </Window.Resources> ``` 而在对应的 C# 代码文件里则可通过以下语句实现对上述自定义颜色的应用: ```csharp var myBrush = new SolidColorBrush((Color)FindResource("MyCustomColor")); textBox.Foreground = myBrush; ``` 这种方法不仅提高了代码可读性和维护性,还便于统一管理界面风格[^3]。 #### 方法三:动态创建 Color 实例并通过 Binding 绑定至 ViewModel 当采用 MVVM 架构开发时,通常会更倾向于利用数据绑定机制而非硬编码的方式去改变 UI 元素的状态。此时可以在 ViewModel 类内部暴露一个表示颜色的对象,并借助 INotifyPropertyChanged 接口通知视图更新显示效果;而实际渲染工作交由 View 来完成。 ViewModel 示例代码可能看起来像这样: ```csharp private Color _highlightColor; public Color HighlightColor { get => _highlightColor; set { if (_highlightColor != value){ _highlightColor = value; OnPropertyChanged(nameof(HighlightColor)); } } } ``` 接着,在相应的 XAML 页面内建立关联关系: ```xml <TextBlock Text="{Binding SomeText}" Foreground="{Binding HighlightColor}"> ... </TextBlock> ``` 这种方式遵循了 MVVM 设计原则,使得业务逻辑与表现层分离得更加彻底[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值