[英]WPF What is the difference between setting the background to transparent and setting opacity on the control?
[英]Setting WPF background Opacity programmatically
我正在开发应用程序,它为数据库中的每一行创建一个新的wpf边框组件。 这意味着我必须在C#而不是XAML中设置边框组件的样式(据我所知)。 除了尝试设置背景不透明度之外,样式都很好。
motherboards.Add(new Border());
Border moboBorder = motherboards[i];
moboBorder.Width = 150;
moboBorder.Height = 150;
moboBorder.BorderBrush = Brushes.Black;
moboBorder.Background = Brushes.White;
moboBorder.CornerRadius = new CornerRadius(10);
moboBorder.Margin = new Thickness(5);
moboBorder.BorderThickness = new Thickness(1);
您可以像这样在XAML中调整背景不透明度
<Border BorderThickness="1" Height="100" Width="100">
<Border.BorderBrush>
<SolidColorBrush Color="Black" Opacity="0.7"/>
</Border.BorderBrush>
</Border>
但正如我所说,我用C#而不是XAML创建组件。 我想这是你在c#中设置值的方式
moboBorder.Background.Opacity = //Value
但是,我无法弄清楚它需要什么样的价值,而不仅仅是一个直线数字,没有什么比我能看到的画笔更像是没有像新的Opacity()
我试过谷歌搜索,但一切都是关于设置整个元素的不透明度而不仅仅是它的背景。
double
肯定是“直线上升”; 将鼠标悬停在属性上以查看数据类型。
问题(谢谢,Clemens)是你试图设置Brushes.Black
的不透明度,这是一个系统对象而你没有做生意。
但您可以设置自己创建的SolidColorBrush
的Opacity
。
要创建一个新的半透明白色画笔:
x.Background = new SolidColorBrush(Colors.White) { Opacity = 0.5 };
请参阅Geoff的答案,了解如何从RGB三元组(或ARGB四元组)而不是命名颜色创建颜色。
或者只是保留现有画笔, 如果你确信你没有从Brushes
获得它。
Background.Opacity = 0.5;
如果你这样做,你从System.Brushes
得到它:
<Window
Background="DeepSkyBlue"
...
如果你这样做,你没有:
<Window.Background><SolidColorBrush Color="DeepSkyBlue" /></Window.Background>
DeepSkyBlue是Colors.DeepSkyBlue
; 你正在用这种颜色创建一个新的画笔。
您应该在XAML中使用绑定执行所有这些操作,而不是在C#中创建WPF控件。 孩子,你会开枪。
但这是你的眼睛。
正如@Clemens在评论中指出:
您无法直接设置系统共享画笔的Opacity
。
您将需要使用非共享的SolidColorBrush
,然后您将能够设置它的Opacity
。
您可以从代码中的任何位置更改Opacity
。
例如:
moboBorder.Background = new SolidColorBrush(Color.FromRgb(255, 0, 0))
{
Opacity = 0.5 // or whatever opacity between
// 0.0 (0%) and 1.0 (100%)
};
要么
moboBorder.Background = new SolidColorBrush(Color.FromRgb(255, 0, 0));
moboBorder.Background.Opacity = 0.5;
与上面的示例类似,如果您使用的是RGB,也可以设置alpha(不透明度)。
您可以使用Color.FromArgb()
静态方法:
moboBorder.Background = new SolidColorBrush(Color.FromArgb(0.5, 255, 0, 0));
只需使用0.0
和1.0
之间的双0.0
(如前所述),作为方法的第一个参数。
希望这可以帮助。
相当于XAML
<Border.BorderBrush>
<SolidColorBrush Color="Black" Opacity="0.7"/>
</Border.BorderBrush>
代码背后会是
moboBorder.Background = new SolidColorBrush
{
Color = Colors.Black,
Opacity = 0.7
};
与Brushes
类中的预定义Brushes(已冻结 )相比,上面的SolidColorBrush可以在以后随时更改,如
moboBorder.Background.Opacity = 0.5;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.