2017-07-16 110 views
1

DataGrid列是在代码后面动态创建的。为了动态绑定列,我有一个Dictionary<string, obj>属性,其中键为列标题和值。启用具有动态创建的“DataGrid”列的`CanUserAddRows` - WPF

和列被绑定到字典是这样的:

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

+0

是您的DataGrid中绑定到一个集合?新项目应该出现在那里。 Columns集合中也应该有一个字符串索引器。例如'dataGrid.Columns [“列名称”]' – opewix

+0

@opewix是的,通常每列都绑定到源集合的属性,在我的情况下,所有列都绑定到一个属性。这是字典,行内的每个单元格都是来自字典的值,其中键是列名。并且在结束编辑时值总是空的。 – IBRA

+0

前段时间我不得不在Silverlight中使用动态列。我使用'List '来进行动态绑定。考虑使用它,如果没有答案 – opewix

回答

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; 
} 

对不起,因为没有完全匹配你的情况,但我现在没有时间了。我希望它会帮助

1

我已经创建了一个测试项目和ExpandoObject为我工作。我能够显示动态栏“姓”,并通过编辑网格行

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; } 
}