t.s*_*htc 5 wpf listview code-behind datatemplate gridviewcolumn
我有一个我在运行时构造的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;
}
Run Code Online (Sandbox Code Playgroud)
上面的示例代码无法正常工作,因为单元格内容仍然与左侧对齐.
小智 14
如果使用DisplayMemberBinding,则不使用CellTemplate.
您必须删除DisplayMemberBinding行并将绑定添加为数据模板的一部分:
private static DataTemplate getDataTemplate(int count)
{
DataTemplate template = new DataTemplate();
FrameworkElementFactory factory = new FrameworkElementFactory(typeof(TextBlock));
factory.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Right);
factory.SetBinding(TextBlock.TextProperty, new Binding(string.Format("[{0}]", count)));
template.VisualTree = factory;
return template;
}
Run Code Online (Sandbox Code Playgroud)
由于您没有在 DataTemplate 中使用 count 属性,因此您只需在 xaml 中创建 DataTemplate,然后您就知道将应用您在 TextBox 上设置的任何属性。就我个人而言,我会使用数据网格并将其设置为只读。它为您提供了创建特定类型的动态列的更大灵活性。
| 归档时间: |
|
| 查看次数: |
9528 次 |
| 最近记录: |