问题描述
|
我有一个在运行时构造的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;
}
上面的示例代码无法正常工作,因为单元格内容仍然向左对齐。
解决方法
由于您没有在DataTemplate中使用count属性,因此可以在xaml中创建DataTemplate,然后您将知道将应用在TextBox上设置的任何属性。我个人将使用Datagrid并将其设置为只读。它为创建特定类型的动态列提供了更大的灵活性。
, 如果使用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;
}