Transparent border in WPF programmatically

2019-04-29 01:47发布

问题:

It's trivial to generate a border (to use for Trackball events) transparent over the viewport in the XAML file:

<Border Name="myElement" Background="Transparent" />

But how do I do it in the .cs?

Border border = new Border();
**border.Background = (VisualBrush)Colors.Transparent;**
grid.Children.Add(viewport);
grid.Children.Add(border);

This does not work of course.

回答1:

This is because you can't just cast a Color to be a Brush. use the Transparent brush instead

border.Background = Brushes.Transparent;


回答2:

Use a SolidColorBrush:

border.Background = new SolidColorBrush(Colors.Transparent);

The VisualBrush has a different purpose. See an overview of the main types of WPF brushes here:

http://msdn.microsoft.com/en-us/library/aa970904.aspx



回答3:

You can also create a SolidColorBrush with transparent color: This will create a fully transparent color

border.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));

but you can also make semitransparent color by changing alpha (this will look like 50% transparent red:

border.Background = new SolidColorBrush(Color.FromArgb(128, 255, 0, 0));