强制WPF DataGrid重新生成自己

Dam*_*cus 7 data-binding wpf datagrid auto-generate

我有一个自定义控件继承自DataGrid并且基本上是2D DataGrid(接受ItemsSource具有两个维度的,例如double[,]).

我添加了一个具体的DependencyPropertyColumnHeadersRowHeaders这样我就可以定义它们.

以下是它现在的工作原理:

  • 我将2D绑定ItemsSourceDataGrid
  • 包装器方法将使用此源将其转换为IEnumerable可绑定到实际数据网格的经典绑定ItemsSource
  • 每行/列自动生成的使用事件完成AutoGeneratingColumn&AutoGeneratingRow以定义它们的报头

问题在这里:

当我初始化时DataGrid,一切正常.

之后,我的应用程序的一个用例定义只有列标题可以更改(通过修改 DependencyProperty ColumnHeaders

而且,无论我在这里做什么,DataGrid都不会重新自动生成其列(因此,标题不会以任何方式更改).

那么,有没有办法问DataGrid一些类似"嘿,我希望你从头重新开始并重新生成列"的方法?因为现在,我无法访问该AutoGeneratingColumn事件,并调用一个方法,例如InvalidateVisual只重绘网格(而不是重新生成列).

这里有什么想法?

我不确定我们是否需要一些代码但是...我会放一些所以没有人要求它:D

    /// <summary>
    /// IList of String containing column headers
    /// </summary>
    public static readonly DependencyProperty ColumnHeadersProperty =
        DependencyProperty.Register("ColumnHeaders",
                                    typeof(IEnumerable),
                                    typeof(FormattedDataGrid2D),
                                    new PropertyMetadata(HeadersChanged));

    /// <summary>
    /// Handler called when the binding on ItemsSource2D changed
    /// </summary>
    /// <param name="source"></param>
    /// <param name="e"></param>
    private static void ItemsSource2DPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        FormattedDataGrid2D @this = source as FormattedDataGrid2D;
        @this.OnItemsSource2DChanged(e.OldValue as IEnumerable, e.NewValue as IEnumerable);
    }

        // (in the constructor)
        AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(DataGrid2D_AutoGeneratingColumn);

    void DataGrid2D_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        DataGridTextColumn column = e.Column as DataGridTextColumn;
        column.Header = (ColumnHeaders == null) ? columnIndex++ : (ColumnHeaders as IList)[columnIndex++]; //Header will be the defined header OR the column number
        column.Width = new DataGridLength(1.0, DataGridLengthUnitType.Auto);
        Binding binding = column.Binding as Binding;
        binding.Path = new PropertyPath(binding.Path.Path + ".Value"); // Workaround to get a good value to display, do not take care of that
    }
Run Code Online (Sandbox Code Playgroud)

Rac*_*hel 7

重置您的ItemsSource,它应该重绘您的DataGrid

void ResetDataGrid()
{
    var temp = myDataGrid.ItemsSource;
    myDataGrid.ItemsSource = null;
    myDataGrid.ItemsSource = temp;
}
Run Code Online (Sandbox Code Playgroud)

您也可以刷新绑定,但我还没有测试它,看看这是否会实际重新生成DataGrid:

void ResetDataGrid()
{
    myDataGrid.GetBindingExpression(DataGrid.ItemsSourceProperty).UpdateTarget();
}
Run Code Online (Sandbox Code Playgroud)