2

I do not want use class properties for binding.

Why it doesn't work? How I can fix this. I get empty rows. I have also manually defined columns for 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;
        }

1 Answer 1

3

First of all, if you're using methods to access directly to your DataGrid properties instead of using data binding, then you should use the DataGrid.Items property, not DataGrid.ItemsSource.

private void Insert(IList<string> row, DataGrid dG)
{
    dG.Items.Add(row);
}

But you'll get empty rows anyway, because the DataGrid has no way of linking each string in your row with the correct column definition.

I think the best approach would be using a converter:

Create the RowIndexConverter class inheriting from IValueConverter, and make so your Convert method looks like this:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    int index = System.Convert.ToInt32(parameter);
    return (value as IList)[index];
}

For this to work, you have to use it in a Binding to an IList property, like the rows of our DataGrid, and pass an index as the ConverterParameter. The XAML would be something like this:

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

Et voila! The values show up. If you want more columns you just have to add them and increment the ConvertParameter. Be careful, as the converter will throw an Exception if the row is not long enough!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.