GridViewColumn CellTemplate 代码背后
我有一个在运行时构造的 listView,即列在编译时未知。
我想将 DataTemplate 应用于单元格,以使 TextAlignment 属性为 TextAlignment.Right。创建列时:
foreach (var col in dataMatrix.Columns)
{
gridView.Columns.Add(
new GridViewColumn
{
Header = col.Name,
DisplayMemberBinding = new Binding(string.Format("[{0}]", count)),
CellTemplate = getDataTemplate(count),
});
count++;
}
private static DataTemplate getDataTemplate(int count)
{
DataTemplate template = new DataTemplate();
FrameworkElementFactory factory = new FrameworkElementFactory(typeof(TextBlock));
factory.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Right);
template.VisualTree = factory;
return template;
}
上面的示例代码无法正常工作,因为单元格内容仍然左对齐。
I have a listView that I construct at run-time, i.e. the columns are not known at compile-time.
I would like to apply a DataTemplate to the cells such that the TextAlignment property is TextAlignment.Right. When creating the columns:
foreach (var col in dataMatrix.Columns)
{
gridView.Columns.Add(
new GridViewColumn
{
Header = col.Name,
DisplayMemberBinding = new Binding(string.Format("[{0}]", count)),
CellTemplate = getDataTemplate(count),
});
count++;
}
private static DataTemplate getDataTemplate(int count)
{
DataTemplate template = new DataTemplate();
FrameworkElementFactory factory = new FrameworkElementFactory(typeof(TextBlock));
factory.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Right);
template.VisualTree = factory;
return template;
}
The sample code above does not work properly as the cell contents is still aligned to the left.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果使用 DisplayMemberBinding,则不会使用 CellTemplate。
您必须删除 DisplayMemberBinding 行并将绑定添加为数据模板的一部分:
If you use DisplayMemberBinding, CellTemplate will not be used.
You must remove the line DisplayMemberBinding and add the binding as part of the data template:
由于您没有在 DataTemplate 中使用 count 属性,因此您只需在 xaml 中创建 DataTemplate,然后您就知道将应用您在 TextBox 上设置的任何属性。就我个人而言,我会使用数据网格并将其设置为只读。它为您提供了创建特定类型的动态列的更大灵活性。
As you are not using the count property in your DataTemplate you could just create the DataTemplate in xaml, then you know that whatever properties you set on the TextBox will be applied. Personally I would use a Datagrid and set it as read only. It gives you more flexibility for creating dynamic columns of specififc types.