嵌套的 xaml 元素 - 在代码中重写它
我需要从代码创建一个 DataGridColumn。 XAML 等效项是:
<data:DataGridTemplateColumn Header="Name" Width="100">
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" TextTrimming="WordEllipsis"></TextBlock>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
我是这样开始的:
DataGridTemplateColumn column = new DataGridTemplateColumn
{
Header = "Name",
Width = 100,
};
TextBlock inside = new TextBlock {TextTrimming = TextTrimming.CharacterEllipsis};
但我不知道如何“合并”这样的谜题。 XAML中有嵌套元素,如何从代码中实现这一点?
I need to create a DataGridColumn from code.
The XAML equivalent would be:
<data:DataGridTemplateColumn Header="Name" Width="100">
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" TextTrimming="WordEllipsis"></TextBlock>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
I've started like that:
DataGridTemplateColumn column = new DataGridTemplateColumn
{
Header = "Name",
Width = 100,
};
TextBlock inside = new TextBlock {TextTrimming = TextTrimming.CharacterEllipsis};
But I don't know how to 'merge' such puzzles. There are nested elements in XAML, how to achieve this from code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
执行此操作的一个好方法是将整个 XAML 代码段打包到一个字符串中,并对其调用 XamlReader.Load() 或 XamlReader.Parse()。这种方法的额外功能是它也可以在 Silverlight 中工作(需要一些调整),在这种情况下您无法在代码中构建
DataTemplate
。A good way to do this is to pack the entire XAML snippet into a string and call XamlReader.Load() or XamlReader.Parse() on it. The bonus feature of this approach is that it'll work in Silverlight as well (with some fiddling), where you can't build
DataTemplate
s in code.差不多就这样,将您的代码更改为这样,它应该可以工作:
除上述之外的另一种方法是在资源中的 XAML 中定义数据模板,然后在代码中动态加载它:
XAML:
代码:
Almost there, change your code to this and it should work:
Another method besides the above is to define your datatemplate in XAML within your resources then dynamically load it in the code:
XAML:
Code: