C# UserControl 可见属性不变

C# UserControl Visible Property Not Changing(C# UserControl 可见属性不变)
本文介绍了C# UserControl 可见属性不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Debug.WriteLine(ucFollow.Visible);
ucFollow.Visible = true;
Debug.WriteLine(ucFollow.Visible);

ucFollow 是一个自定义的 UserControl,没什么花哨的.上面的代码打印出来:

ucFollow is a custom UserControl, nothing fancy. The above code prints out:

False
False

最糟糕的是,这确实切换了 UserControl 的实际可见性(即,一旦调用此代码,ucFollow 就会出现),但似乎 Visible 属性以某种方式不是......好吧,在后端可见,并且不反映更改,即使 UI 本身也是如此.

Worst part is, this does toggle the actual visibility of the UserControl (i.e. ucFollow does appear once this code is called), but it seems somehow that the Visible property isn't ... well, visible on the backend, and doesn't reflect the change, even though the UI itself does.

我什至不知道从哪里开始解决这个问题.有没有人知道什么可能会导致这种疯狂?

I don't even know where to begin troubleshooting this. Does anyone have any ideas as to what could remotely cause this kind of craziness?

这是 Visual Studio 2010 中的标准 C# WinForm.

This is with a standard C# WinForm in Visual Studio 2010.

推荐答案

我没有破坏 C#!:)

I didn't break C#! :)

原来罪魁祸首是 Form.Visible 属性.在 Form.Visible 设置为 true 之前,表单上的所有控件都将不可见(Visible = false).

Turns out the culprit was the Form.Visible property. Before Form.Visible is set to true, any and all controls on the form will be invisible (Visible = false) no matter what.

但是,您仍然可以设置可见属性 - 它们只是在 Form.Visible 属性设置为 true 之前不会生效.

However, you can still set Visible properties - they just won't take effect until the Form.Visible property is set to true.

换句话说,当我调用 ucFollow.Visible = true 时,我的程序确实在注册它 - 然而,在代码中,ucFollow 的父 Form.Visible 仍然是 false.因此,调试器和我的打印语句都识别出,嘿,这个控件的父窗体仍然不可见,所以这个控件不可见.句号."

In other words, when I called ucFollow.Visible = true, my program was indeed registering it - however, at that point in the code, ucFollow's parent Form.Visible was still false. Therefore, both the Debugger and my print statements recognized, "Hey, this control's parent form is still not visible, so this control is not visible. Period."

一旦表单可见,所有更改都会生效,一切正常.

As soon as the form was made visible, all the changes took effect and everything worked great.

故事的寓意:不要依赖控件的可见性属性,除非包含它们的表单已经可见并正在运行.

Moral of the story: Don't rely on the Visibility properties of your controls unless the form containing them is already visible and running.

这篇关于C# UserControl 可见属性不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)