Search code examples
c#wpfopacity

Setting WPF background Opacity programmatically


I'm working on application which creates a new wpf border component for each row in a database. This means I've got to style the border component in C# rather than XAML (as far as I'm aware). The styling is all good so far apart from trying to set the background opacity.

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);

You can adjust the background opacity in XAML like so

<Border BorderThickness="1" Height="100" Width="100">
    <Border.BorderBrush>
        <SolidColorBrush Color="Black" Opacity="0.7"/>
    </Border.BorderBrush>
</Border>

But as I've said I'm creating the component in C# rather than XAML. I guess this is how you set the value in c#

moboBorder.Background.Opacity = //Value

However, I can't figure out what kind of value it takes, not just a straight up number, nothing from brushes than I can see and nothing like = new Opacity()

I've tried googling around but everything is about setting the opacity for the whole element rather than just the background of it.


Solution

  • A double is certainly a "straight up number"; hover the mouse over the property to see the data type.

    The problem (thanks, Clemens) is that you're trying to set the opacity of Brushes.Black, which is a system object and you've got no business doing that.

    But you can set the Opacity of a SolidColorBrush that you create yourself.

    To create a new semi-opaque white brush:

    x.Background = new SolidColorBrush(Colors.White) { Opacity = 0.5 };
    

    See Geoff's answer for how to create a color from an RGB triplet (or ARGB quad) instead of named colors.

    Or just keep the existing brush, if you're confident that you didn't get it from Brushes.

    Background.Opacity = 0.5;
    

    If you did this, you got it from System.Brushes:

    <Window
        Background="DeepSkyBlue"
        ...
    

    If you did this, you didn't:

    <Window.Background><SolidColorBrush Color="DeepSkyBlue" /></Window.Background>
    

    That DeepSkyBlue is Colors.DeepSkyBlue; you're creating a new brush with that color.

    You should be doing all of this in XAML with bindings instead of creating WPF controls in C#. You'll shoot your eye out, kid.

    But it's your eye.