【发布时间】:2021-02-28 22:41:16
【问题描述】:
我试图在代码隐藏中的 ListView 中居中列。由于列是在运行时动态创建的,因此在 XAML 中没有执行此操作的选项。
这里是我创建的助手。设置字体颜色等其他属性效果很好 - 有什么想法吗?
private void ListViewHelper(GridView gridView, ListView listView, MatrixId assignment, string key, IValueConverter converter)
{
// new column
GridViewColumn gridViewColumn = new GridViewColumn();
// header text and formating
gridViewColumn.Header = new TextBlock { Text = assignment.Id.ToString(), TextAlignment = TextAlignment.Center, Padding = new Thickness(7, 0, 0, 0), Width = 50 };
// databinding & converter
FrameworkElementFactory frameworkElementFactory = new FrameworkElementFactory(typeof(TextBlock));
DataTemplate dataTemplate = new DataTemplate();
dataTemplate.VisualTree = frameworkElementFactory;
gridViewColumn.CellTemplate = dataTemplate;
Binding binding = new Binding(assignment.Id.ToString() + key);
binding.Converter = converter;
// *** this does not work ***
frameworkElementFactory.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Right);
frameworkElementFactory.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Right);
frameworkElementFactory.SetValue(TextBlock.ForegroundProperty, new SolidColorBrush(Color.FromRgb(100, 100, 100)));
frameworkElementFactory.SetBinding(TextBlock.TextProperty, binding);
// add column
gridView.Columns.Add(gridViewColumn);
}
【问题讨论】:
标签: c# wpf listview gridview code-behind