您的位置:首页 > 其它

winphone动态生成textBlock、image等控件

2013-09-05 22:53 246 查看
若在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中要换成‘’;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: