winphone動態生成textBlock、image等控件

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章