2015-10-07 54 views
-1

我想使用XAML代码在控制器中创建文本块。这是可能的吗?任何其他想法?如何使用XAMLReader在控制器中创建文本块

 // Create a string 
     String sb = "<TextBlock Name='NameLabel' HorizontalAlignment='Left' TextWrapping='Wrap' FontSize='37.333' FontFamily='Intel Clear Light' Opacity='0.5' Width='277' Grid.Row='4' Grid.ColumnSpan='3' Grid.Column='1' Text='Name (as per IC)' Margin='1,0,0,80' Grid.RowSpan='2'/>"; 

     // Create a textblock using a XamlReader 
     TextBlock myTextBlock = (TextBlock)XamlReader.Load(sb.ToString()); 

     // Add created button to previously created container. 
     splMain.Children.Add(myTextBlock); 
+0

如何只创建TextBlock对象通常('新的TextBlock()'等等)?或者也许使用数据绑定/模板让WPF为你创建它?这取决于你的确切场景。 – vesan

+0

我的场景是我想推XAML代码,就像在控制器中并在XAML中显示。 –

+0

是的,我明白这个问题。虽然XAML字符串来自哪里?是否有可能在代码中创建元素?如果没有,你的代码有什么问题?它工作吗?它是否会抛出异常? – vesan

回答

0
 I have change my code. And now I have an error of [ splMain.Children.Add(myTextBlock); Additional information: Object reference not set to an instance of an object.] 
     // Create a string 
     String sb = "<TextBlock xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Text=\"Name (as per IC)\" Margin=\"1,0,0,80\" Grid.RowSpan=\"2\"/>"; 

     // Create a textblock using a XamlReader 
     TextBlock myTextBlock = (TextBlock)XamlReader.Load(sb.ToString()); 

     // Add created button to previously created container. 
     splMain.Children.Add(myTextBlock);