简体   繁体   English

C#WPF使用另一个窗口上的按钮控制标签不透明度

[英]C# WPF controlling label opacity with a button on a different window

I got a small program which uses 2 transparent windows. 我有一个使用2个透明窗口的小程序。 To position them i added a small colored label. 为了放置它们,我添加了一个小的彩色标签。 I got this on both transparent windows. 我在两个透明窗口上都看到了这个。 Transparent window1 has 2 buttons increase and decrease opacity. 透明window1有2个按钮,可增加和减少不透明度。 This button works for transparent window1 but not for transparent windows2. 此按钮适用于透明window1,但不适用于透明windows2。

 private void BtnIncreaseOpacity_Click(object sender, RoutedEventArgs e)
{
lblDrag.Opacity = 100;
win2.lblDrag2.Opacity = 100;
}

In the Public partial class 在公共部分课程中

TrackerMessage win2 = new TrackerMessage();

The code is accepted, but it does not work. 该代码被接受,但是不起作用。 So i am pretty sure this is doing something different then i think. 所以我很确定这是在做一些与我想不同的事情。

The other problem is similar. 另一个问题是相似的。 the transparent windows2(win2) needs to make its labels visible when a timer on transparent window1 reaches 0. But thats more of the same problem, since right now you cannot access anything from window1 on window2 当透明window1上的计时器达到0时,透明windows2(win2)需要使其标签可见。但这更是同一个问题,因为现在您无法从window2上的window1访问任何内容

So the question is, what am i doing wrong. 所以问题是,我在做什么错。

Really, both Opacity properties should be bound to a view model and then the button's command modifies the backing properties (allowing the UI to update). 实际上,两个不透明度属性都应绑定到视图模型,然后按钮的命令修改后备属性(允许UI更新)。

That said, at the very least you should have each window handling its own UI (and I suspect that is the problem). 就是说,至少您应该让每个窗口都处理自己的UI(我怀疑这是问题所在)。 Instead of setting the property directly for win2, have it call a function: 与其直接为win2设置属性,不如让它调用一个函数:

win2.SetOpacity(100);

Where SetOpacity looks like: SetOpacity如下所示:

public void SetOpacity(int newValue)
{
   lblDrag2.Opacity = newValue;
}

You may also need to do a Dispatcher.BeginInvoke (since this is being called from the other window's UI thread). 您可能还需要执行Dispatcher.BeginInvoke(因为这是从另一个窗口的UI线程调用的)。 In that case, the function is: 在这种情况下,该函数为:

public void SetOpacity(int newValue)
{
   Dispatcher.BeginInvoke(new Action(() =>
   {
      lblDrag2.Opacity = newValue;
   }));
}

Let me know if I can clarify anything! 让我知道我是否可以澄清任何事情!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM