Setting Opacity On a Parent Element different than child element in WPF

550 Views Asked by At

I am trying t simulate a 'modal' type event in my application that will give a transparent background 'dimming' feel, and a form that will have content in it.

The problem I am running into is I am setting the opacity on the overlay canvas, and it is inherited on the child form.

This is shown in the screenshot below. You can still see corner of background items.

enter image description here

The code I am using is the following:

protected void Draw(DrawingContext drawingContext)
    {
        //Crate Overlay Canvas
        Canvas canvas = new Canvas();
        canvas.Width = ((Canvas)this.AdornedElement).ActualWidth;
        canvas.Height = ((Canvas)this.AdornedElement).ActualHeight;
        canvas.Opacity = .4;
        canvas.Background = new SolidColorBrush(Colors.Black);

        //Create Form Panel
        StackPanel panel = new StackPanel();
        panel.Background = new SolidColorBrush(Colors.White);
        panel.Width = 400;
        panel.Height = 200;
        panel.Opacity = 1; //Just to make sure

        Button button = new Button();
        button.Content = "Test Button";
        button.Height = 30;

        panel.Children.Add(button);

        Canvas.SetLeft(panel, canvas.Width/2);
        Canvas.SetTop(panel, canvas.Height/2);

        canvas.Children.Add(panel);

        Content = canvas;
    }
1

There are 1 best solutions below

0
McGarnagle On

Should be easily solved -- create another parent Canvas, and add both the overlay and panel to it separately. That way the panel will be the overlay's sibling instead of its child, and won't inherit the opacity. Eg:

protected void Draw(DrawingContext drawingContext)
    {
        var wrapper = new Canvas();

        // ...

        wrapper.Children.Add(canvas);
        wrapper.Children.Add(panel);

        Content = wrapper;
    }