c# - 设置矩形的不透明度

标签 c# wpf

点击某个按钮时会触发一个事件

private void set_Opacity(object sender, RoutedEventArgs e)
    {
        this.Opacity = 0;
    }

但是点击按钮没有任何效果。我究竟做错了什么? 谢谢。

编辑: 我将介绍一些我正在尝试做的事情的背景:

我已经创建了一个自定义按钮,它应该使用淡出动画最小化我的窗口,所以这是它的代码:

 private void minimize_Window(object sender, EventArgs e)
    {
        var anim = new DoubleAnimation(0, (Duration)TimeSpan.FromSeconds(1));
        anim.Completed += (s, _) => this.Minimize();
        this.BeginAnimation(UIElement.OpacityProperty, anim);



    }
    private void Minimize()
    {
        WindowState = WindowState.Minimized;
    }

它工作得很好,但问题是当我尝试从任务栏中检索我的程序时它不会执行任何操作(当我在最小化后从任务栏中单击它时我无法看到该程序).我从中了解到,我的程序的不透明度在最小化时被设置为 0(由于动画)。 所以我使用 Activated 事件调用该方法:

private void set_Opacity(object sender, EventArgs e)
    {
        rectangle2.Opacity = 1;
        WindowState = WindowState.Normal;
    }

同样的问题。希望你能帮忙。

非常感谢。

最佳答案

问题似乎是在大多数情况下,this 将成为一个Window。不过,我的假设是,您并没有试图将整个窗口设置为不可见,而是设置为一个矩形。您需要使用 x:Name 属性为您的 Rectangle 命名。这是一个例子:

<Rectangle Width="40" Height="40" x:Name="MyRectangle" Fill="Red" />

然后,在您的按钮中单击:

private void set_Opacity(object sender, RoutedEventArgs e)
{
    MyRectangle.Opacity = 0;
}

如果你真的想设置整个Window的透明度:

除非您在 XAML 中将 AllowTransparency 指定为 true 并将 WindowStyle 指定为 None,否则整个 Window 不能设置不透明度:

<Window x:Class="ScratchApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        AllowsTransparency="true" WindowStyle="None">

注意正在设置的属性。

编辑:

I need an event to be fired when my program is being activated back from my task bar. Do you have any idea what event I could use?

使用 Window.Activated 事件。从您的 XAML:

<Window Activated="Window_Activated">

在你的 C# 中:

private void Window_Activated(object sender, EventArgs e)
{
    //Put code here
}

关于c# - 设置矩形的不透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11065023/

相关文章:

c# - 如何在DataGridTextColumn中获取文本像素大小

c# - 如何更新使用 Windows 安装程序技术部署的 WPF 应用程序

c# - 我如何创建特定编号的 ListView。 WPF 中的列数?

c# - SqlDependency - 防止事件之间的数据丢失并再次重新注册查询?

c# - 部署 .NET Core 站点时,Ajax 调用返回 401

c# - 将图像转换为 byte[] c# 并在 android 中取回图像

c# - ssl webservice中的自定义用户名/密码

c# - 使用 ABP 框架自定义 API 响应 HTTP 状态码

c# - 用下划线替换字符串空格

.net - WPF 内存泄漏