c# - 在与 WPF 中的子元素不同的父元素上设置不透明度

标签 c# wpf winforms adorner adornerlayer

我正在尝试在我的应用程序中模拟一个“模态”类型的事件,它将提供透明背景“变暗”的感觉,以及一个包含内容的表单。

我遇到的问题是我在覆盖 Canvas 上设置不透明度,它是在子窗体上继承的。

这显示在下面的屏幕截图中。您仍然可以看到背景项目的一角。

enter image description here

我使用的代码如下:

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

最佳答案

应该很容易解决——创建另一个父 Canvas,并分别向其添加叠加层和面板。这样面板将成为叠加层的兄弟而不是其子项,并且不会继承不透明度。例如:

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

        // ...

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

        Content = wrapper;
    }

关于c# - 在与 WPF 中的子元素不同的父元素上设置不透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23692459/

相关文章:

c# - XStreamingElement 作为 XDocument 的一部分

c# - 显示动画直到操作完成 wpf

c# - 将控件绑定(bind)到 WPF 中的集合/数组中的单个值

winforms - 最 "lightweight"的winforms控件是什么?

C# 名称进程

c# - 将 List<Guid> 转换为 List<Guid? >

c# - 从数据读取器填充对象

c# - UserControl 具有传播到内部控件的绑定(bind)

c# - 自定义 DataGridViewCheckBoxCell 视觉更新在编辑模式下不起作用

c# - 调用时的方法实际上递归地调用自身