Jedi Master
Jedi Master

Reputation: 59

WPF DataGrid binding to property in subclass

I'm trying to wrap my head around how to properly bind a datagrid column with data in a subclass. To clear things up, I've done a little sample which, if resolved, would greatly help in making the code work.

Here are the classes defined:

public class SubItem
    {
        public string Data { get; set; }
    }

public class Item
    {
        public int Value { get; set; }
        public SubItem Data { get; set; }
    }

I then create an observablecollection as follows:

public class IntData : ObservableCollection<Item>
    {
        public IntData() : base()
        {
            Item i = new Item() { Value = 56, Data = new SubItem() { Data = "testdata" } };
            Add(i);
        }
    }

And here is my MainWindow code:

public partial class MainWindow : Window
    {
        public IntData Integers { get; set; }

        public MainWindow()
        {
            Integers = new IntData();

            InitializeComponent();
            dataGrid1.ItemsSource = Integers; // This is an important line
        }
    }

The XAML code is kept simple:

<DataGrid Name="dataGrid1" AutoGenerateColumns="False" Margin="12">
   <DataGrid.Columns>
      <DataGridTextColumn Header="Integers" Binding="{Binding Value}"/>
      <DataGridTextColumn Header="Data" Binding="{Binding Data}"/>
   </DataGrid.Columns>
</DataGrid>

enter image description here

Running the above, you will notice that the Integers is working as it should but not the Data column. Any ideas from anyone on how to make that column show the Data property? Thanks in advance!

Upvotes: 0

Views: 1516

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23298

The easiest way to fix it is to override ToString() method in SubItem class and return Data property

public class SubItem
{
    public string Data { get; set; }

    public override string ToString()
    {
        return Data;
    }
}

Another option is update DataGridTextColumn binding and use Data sub-property of Data property from Item class (you'll probably need to update a naming:))

<DataGridTextColumn Header="Data" Binding="{Binding Data.Data}"/>

More complicated option is to use DataGridTemplateColumn and define your own template to represent a data

<DataGridTemplateColumn Header="Data">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Data.Data}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Upvotes: 1

Related Questions