作为一个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>
运行后的结果如下:

精彩图集精彩文章热门标签
Iisftp.vbs linux使用 360 见解 scp 使用指南 menu 测试 宽字节字符 字母数字组合 httpclient 判断编 SqlServer200 0day JVM性能优化 nfc应用 引擎 开发环境 SWF动画截图 独立 goto函数 delegate infile LIFO promise化 总记录 Parse 后台运 80004005 Nginx访问日志 细粒度审计 文件编码 SQL-INJECTIO 选项值 变量命名 linux安装mysql MySQL索引 倒计时跳转 调整列宽 数字相加 触摸事件 元素移动 索引器 c异或运算 远程拷贝 应用程序开发 行政区划数据 强制不换行 编译python $.post 文件目录操作 添加CSS类 ListActivity 开启curl 动态树 彩图 filter essential NGEN 双网关赞助商链接
♦▐返回顶部@CopyRight 2002-2008, 1SOHU.COM, Inc. All Rights Reserved QQ:1010969229

