作为行的字符串的WPF DataGrid绑定列表

作为行的字符串的WPF DataGrid绑定列表,wpf,binding,datagrid,Wpf,Binding,Datagrid,我不想使用类属性进行绑定 为什么它不起作用?我怎样才能解决这个问题。我有空行。我还为DataGrid手动定义了列 private void Insert(IList<string> row, DataGrid dG) { ObservableCollection<IList<string>> data = dG.ItemsSource as ObservableCollection<IList<string

我不想使用类属性进行绑定

为什么它不起作用?我怎样才能解决这个问题。我有空行。我还为DataGrid手动定义了列

 private void Insert(IList<string> row, DataGrid dG)
        {
            ObservableCollection<IList<string>> data = dG.ItemsSource as ObservableCollection<IList<string>>;
            data.Add(row);
            dG.ItemsSource = data;
        }
private void Insert(ILST行,DataGrid dG)
{
ObservableCollection数据=dG.ItemsSource作为ObservableCollection;
添加数据(行);
dG.ItemsSource=数据;
}

首先,如果您使用方法直接访问DataGrid属性,而不是使用数据绑定,那么您应该使用DataGrid.Items属性,而不是DataGrid.ItemsSource

private void Insert(IList<string> row, DataGrid dG)
{
    dG.Items.Add(row);
}
为了实现这一点,您必须在绑定到IList属性(如DataGrid的行)时使用它,并将索引作为ConverterParameter传递。XAML应该是这样的:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    int index = System.Convert.ToInt32(parameter);
    return (value as IList)[index];
}
<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Test"
    Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:RowIndexConverter x:Key="rowIndexConverter" />
    </Window.Resources>
    <Grid>
        <DataGrid x:Name="DataGrid">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding ., Converter={StaticResource rowIndexConverter}, ConverterParameter=0}" />
                <DataGridTextColumn Binding="{Binding ., Converter={StaticResource rowIndexConverter}, ConverterParameter=1}" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

瞧!这些值会显示出来。如果需要更多的列,只需添加它们并增加ConvertParameter。小心,因为如果行不够长,转换器将抛出异常