GridViewColumn CellTemplate代码背后

时间:2011-06-14 20:31:39

标签: wpf listview datatemplate code-behind 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;
}

上面的示例代码无法正常工作,因为单元格内容仍然与左侧对齐。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:2)

由于您没有在DataTemplate中使用count属性,您只需在xaml中创建DataTemplate,然后您就会知道您在TextBox上设置的任何属性都将被应用。我个人会使用Datagrid并将其设置为只读。它为您创建特定类型的动态列提供了更大的灵活性。

相关问题