作为一个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>
运行后的结果如下:
精彩图集精彩文章热门标签
$.browser mvc3 本窗口 销毁目录 p HUP信号 限制IP 引用和类属性 js调用后台 程序模 php读取大文件 str_repeat函数 s:date 挂载目录 ADO.NET 各种形式 php php实现字 选择文件 Response.Cha 数组详解 360通用防护 exists DataSet 函数实例 释放被锁 SendKey C语言程 自动缩进 (第3篇) 重排序 ins_emdb.mk php php链接 jaxb kangle getRequestDi 预读 傅里叶变换 信息监听 PHP异常处 墙上 恢复 主机控制 显示表 杨辉三角形 警告 下拉树 狗狗影视 图片库 宽度 再次点击 python模拟登陆 知道 status 重复字段 php php中以只 des加密解密 表损坏 映射 汉字 当前系统时间 爬虫程序赞助商链接
@CopyRight 2002-2008, 1SOHU.COM, Inc. All Rights Reserved QQ:1010969229