使用动态创建的`DataGrid`列启用`CanUserAddRows` - WPF

时间:2017-07-16 10:02:18

标签: c# wpf xaml datagrid

DataGrid列是在代码后面动态创建的。为了动态绑定列,我有一个Dictionary<string, obj>属性,键作为列标题和值。

并且列绑定到字典,如下所示:

var item = new DataGridTextColumn();
item.Width = new DataGridLength(1, DataGridLengthUnitType.Auto);
item.Header = name;
item.Binding = new Binding($"di[{name}].obj") { Mode = BindingMode.TwoWay };

它工作正常,但我无法弄清楚如何从新行格式DataGrid获取值

2 个答案:

答案 0 :(得分:1)

我创建了一个测试项目,ExpandoObject为我工作。我能够显示动态列“FirstName”,还可以通过编辑网格行来添加新行

XAML:

<Grid Margin="0,0,0,56" Loaded="Grid_Loaded_1">
    <DataGrid Name="MyGrid" ItemsSource="{Binding Items}" HorizontalAlignment="Left" Margin="69,33,0,0" VerticalAlignment="Top" Height="220" Width="389"/>
    <Button Content="Button" HorizontalAlignment="Left" Height="22" Margin="339,286,0,-45" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>

CS:

public partial class MainWindow : Window
{
    public ViewModel Vm { get; set; }

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Grid_Loaded_1(object sender, RoutedEventArgs e)
    {
        Vm = new ViewModel();
        Vm.Items = new ObservableCollection<ExpandoObject>();
        DataContext = Vm;

        var fieldName = "FirstName";
        var item = new ExpandoObject() as IDictionary<string, Object>;
        item.Add(fieldName, "Adam"); // Dynamically adding new fields

        var eoItem = item as ExpandoObject;
        Vm.Items.Add(eoItem);

        // Dynamically adding new columns
        var col = new DataGridTextColumn();
        col.Width = new DataGridLength(1, DataGridLengthUnitType.Auto);
        col.Header = fieldName;
        col.Binding = new Binding(fieldName) { Mode = BindingMode.TwoWay };
        MyGrid.Columns.Add(col);
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {

    }
}

public class ViewModel
{
    public ObservableCollection<ExpandoObject> Items { get; set; }
}

答案 1 :(得分:0)

前段时间我遇到过类似的问题。下面你可以找到我的解决方案。基本上我需要更改AddingNewRow事件。您需要更改类型等以满足您的需求,但这应该很容易。

private void AddingNewRow(object sender, AddingNewItemEventArgs e)
{
    DictionaryRowData newRow = new DictionaryRowData();
    for (int i = 0; i < dictionaryData.Columns.Count; i++)
    {
        newRow.Cells.Add(new DictionaryCellData());
    }

    e.NewItem = newRow;
}

对不起,因为不完全符合您的情况,但我现在没有时间。我希望它会有所帮助