.NET TreeView将不显示图像
时间:2020-03-06 14:38:51 来源:igfitidea点击:
获取TreeView控件以显示节点图像时遇到问题。下面的代码有时可以工作,但在其他时间无法显示任何图像。
private TreeNode AddNodeForCore(TreeNode root, Core c) { string key = GetImageKey(c); TreeNode t = root.Nodes.Add(c.Name, c.Name, key, key); t.Tag = c; return t; }
请注意,当失败时,TreeView将无法显示任何节点的任何图像。 TreeView确实分配了一个ImageList,并且图像键肯定在图像集合中。
编辑:
我的谷歌福很弱。真不敢相信我自己没有找到答案。
解决方案
快速的Google搜索找到了以下答案:http://forums.microsoft.com/MSDN/ShowPost.aspx?siteid=1&PostID=965968
从该页面引用:
If the Form containing the TreeView is instantiated in the add-in startup function as below, the icons appear!
public partial class ThisApplication { Form1 frm; private void ThisApplication_Startup(object sender, System.EventArgs e) { frm = new Form1(); frm.Show(); }
BUT, if instantiated with the class, as below:
public partial class ThisApplication { Form1 frm = new Form1(); private void ThisApplication_Startup(object sender, System.EventArgs e) { frm.Show(); }
Then they do NOT appear. Furthermore, if "VisualStyles" (new with XP) are disabled, the icons work in both instances.
上面的googleed帖子有用的一点是:
"这是Windows XP视觉样式实现中的一个已知错误。某些控件(如ImageList)在应用调用Application.EnableVisualStyles()之前在创建它们时未正确初始化。 Program.cs避免了这种情况。感谢回复!"
因此,基本上,在初始化图像列表之前,请确保已调用Application.EnableVisualStyles()。
根据MSDN库中的添加方法部分,我们需要同时填充TreeView.ImageList
和TreeView.SelectedImageList
,因为第四个参数引用了第二个列表。
如果在选择节点时发生此错误,则不要再寻找了。
Yossarian发布的解决方案或者流行的"在Application.EnableVisualStyles()和Application.Run()之间调用Application.DoEvents()"对我都有效。
经过大量的打滑,咬牙切齿和谷歌搜索之后,Addy Santo发布的解决方案成功了。