winphone动态生成textBlock、image等控件

本文介绍如何在C#代码中使用XamlReader轻松动态生成XAML控件,包括TextBlock和Image实例,详细解释了命名空间引用、XAML字符串格式化以及转换过程中的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

若在cs代码中如XAML生成控件一样简单就好了。

当然!办法永远都比困难多。

 

引用命名空间:

using System.Windows.Markup;//       XamlReader

 

在需要动态生成textBlock的地方写如下代码:

 

//可以先在form上拖一个自己想要的textBlock,之后复制下来它的相关XAML语言,放到一个string s里面

string s = @"<TextBlock 
xmlns='http://schemas.microsoft.com/client/2007' 
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' 
FontSize='{StaticResource PhoneFontSizeMediumLarge}'
VerticalAlignment='Top'
Height='40'
Margin='34,34,0,0'
Name='tb'
Text='地区:'
/>";

 

//通过XamlReader,我们可以将s读出来,并转换成相应的object

TextBlock tbArea = XamlReader.Load(s) as TextBlock;

 

后续:

我们可以将创建好的这个tb加入到Grid里面,代码如下:

Grid gd = new Grid();

gd.Children.Add(tbArea);

 

若想动态生成一个image,只需转换string s即可

string sImage =

@"<Image 
xmlns='http://schemas.microsoft.com/client/2007'  
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' 
Height='90'
HorizontalAlignment='Left'
Margin='40,232,0,0'
Name='image'
Stretch='Uniform'
VerticalAlignment='Top'
Width='90' />";

 

注意两点

1:

xmlns='http://schemas.microsoft.com/client/2007'

xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'

这两句话一定不能丢,否则会转换报错!

2:

原XAML语言中的“”号在string中要换成‘’;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值