若在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中要换成‘’;