[英]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.