我正在尝试为列标题创建带有标签和组合框的自定义列。 第一次正确加载网格。单击该按钮,我更改了Datagrid的itmesources。我看到datagrid的单元格已更新,但不会更新标题。我还看到没有调用Datagrid_Loaded。在调试时我发现对于“绑定”对象,我提供绑定路径,但对于标题,我提供源,因此标题不会更新。如何为标题提供路径,使其类似于绑定?
private void DataGrid_Loaded(object sender, RoutedEventArgs e)
{
DataGrid grid = sender as DataGrid;
if (grid.Items.Count == 0)
{
return;
}
StageVM data = grid.Items[0] as StageVM;
if (data == null)
{
return;
}
int index = 0;
foreach (StageItemVM param in data.Stage)
{
var binding = new Binding(string.Format("Stage[{0}].StageItem.Value", index));
grid.Columns.Add(new CustomBoundColumn()
{
CanUserSort = false,
HeaderTemplateSelector = this.FindResource("ColumnHeaderTemplateSelector") as DataTemplateSelector,
HeaderStyle = this.FindResource("StageHeaderStyle") as Style,
Header = (new Binding().Source = param.StageItem.Key),
Binding = binding,
TemplateSelectorName = "StageRangeColumnTemplateSelector"
});
index++;
}
}
customBoundColumn类如下:
public class CustomBoundColumn : DataGridBoundColumn
{
public string TemplateSelectorName { get; set; }
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
var binding = new Binding(((Binding)Binding).Path.Path);
binding.Source = dataItem;
var content = new ContentControl();
content.ContentTemplateSelector =(DataTemplateSelector)cell.FindResource(TemplateSelectorName);
content.SetBinding(ContentControl.ContentProperty, binding);
return content;
}
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
{
return GenerateElement(cell, dataItem);
}
}
答案 0 :(得分:0)
检查这是否可以帮助您: WPF DataGridTextColumn header binding
我遇到了与我的ViewModel绑定datagrid标头相同的问题。这是一个基于xaml的解决方案。