我在Grid(xaml)中定义了一个textblock visual_name,用作以编程方式将文本块添加到网格中的视觉提示
如何将visual_name的所有属性复制到以编程方式创建的文本块(txtblock)?
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock x:Name="visual_name" HorizontalAlignment="Left" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" RenderTransformOrigin="0.419,0.528" Margin="84,187,0,0" Width="220" Foreground="#FF0E0E0E"/>
<TextBlock x:Name="visual_point" HorizontalAlignment="Left" Margin="352,187,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="102" Height="28" Foreground="Black"/>
<TextBlock x:Name="visual_rank" HorizontalAlignment="Left" Margin="10,186,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="56" Height="28">
</TextBlock>
</Grid>
我的C#代码:
foreach(Leaders leader in listofleaders )
{
TextBlock txtblock = new TextBlock();
//copy properties of visual_name to txtblock
txtblock.Text = leader.name;
// add margin
LayoutRoot.Children.Add(txtblock);
}
答案 0 :(得分:0)
我认为你想要克隆你的Textblock对象。也许您可以在XamlWriter
命名空间中尝试System.Windows.Markup
。
可能下面的代码可以提供帮助。
在xaml中写入文本块并获得一个字符串作为回报。
string visualNameXaml = XamlWriter.Save(visual_name);
然后您可以使用以下代码进行检索。
StringReader stringReader = new StringReader(visualNameXaml);
XmlReader xmlReader = XmlReader.Create(stringReader);
TextBlock newTextBlock = (TextBlock)XamlReader.Load(xmlReader);
执行此操作后,您可以动态添加文本块。 希望这有帮助!。