作为一个WPF控件开发者,我在工作中经常遇到如本文标题所示的问题。其实,这个问题并不是很难,只是在操作上有些繁琐。本文将尝试对这个问题进行解答,并且对相关的一些技术细节加以探讨。
先从我遇到的一个典型的问题开始吧:写一个MyElement类,要求如下:
-
从FrameworkElement继承增加一个Button到它的VisualTree上
在Visual上有一个AddVisualChild方法,相信很多刚接触这个方法的同学们(好吧,至少我是这样)都会“顾名思义”地认为这个方法就可以解决本文的问题。再加上MSDN上也给出了一个例子来“火上浇油”一把。于是,一阵窃喜之后,我兴奋地敲出了以下代码:
C# Code [http://www.xueit.com]
class MyElement : FrameworkElement { private Button _button = new Button() { Content = "I'm a Button!"}; public MyElement() { this.AssembleVisualChildren(); } private void AssembleVisualChildren() { this.AddVisualChild(this._button); } protected override int VisualChildrenCount { get { return 1; } } protected override Visual GetVisualChild(int index) { return this._button ; } }
然后将这个MyElement加入测试窗口,代码如下:
Code [http://www.xueit.com]
<Window x:Class="AddVisualChildTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:loc="clr-namespace:AddVisualChildTest" WindowStartupLocation="CenterScreen" Title="Window1" Height="300" Width="300"> <Grid> <loc:MyElement Margin="10"/> </Grid> </Window>
运行后的结果如下:

精彩图集精彩文章热门标签
Oracle数据库 ctype函数 mysql小技巧 MIME II 超链接 js操作table PHP框架 hashing des加密 vspace SessionFacto print_r 抓取豆瓣 创建 o squid jsp操作MySQL 加减 则是 COLOR Shell.Applic jira 起止时间 当前url c00ce56e 消息窗口 nagios飞信监控 in_array RAC http 提交数据 内存管理 计算机 手电筒 pytho 过滤排序 oracle下载 大类 数组查询 传输 APPPOOL 漫画 技能 python代码检查 硬件列表 访问远程文 基础 纯属疑问 之双 php程序员 验证 浅谈 GPS功能 多个定时器 我所 改变按钮 数据存储 数据库主键 除法运算 文件夹赞助商链接
♦▐返回顶部@CopyRight 2002-2008, 1SOHU.COM, Inc. All Rights Reserved QQ:1010969229

