Ewerton
Ewerton

Reputation: 4523

How to bind a related object property to a TextBlock in DataGridTemplateColumn with WPF

I have two objects Exercise and Objective, each Exercise has one Objective. In the code behind I set the ItemsSource of the Exercises DataGrid

 dgExercicios.ItemsSource = Repositorio<Exercicio>.GetAll();

And in my XAML.

    <DataGrid Name="dgExercicios" CellStyle="{StaticResource CellStyle}" CanUserSortColumns="True" CanUserResizeColumns="True" AutoGenerateColumns="False">
         <DataGrid.Columns>
             <!--This bind works (Exercice.Nome)-->
             <DataGridTextColumn Header="Nome" Binding="{Binding Nome}" Width="200"   />
             <!--This bind DONT works (I Trying to bind to Exercise.Objective.Descricao)-->                     
             <DataGridTemplateColumn Header="Objetivo"  Width="80" >
                     <DataGridTemplateColumn.CellTemplate>
                         <DataTemplate  >
                             <StackPanel>
                                 <TextBlock Text="{Binding Path=Objective.Descricao}" T />
                              </StackPanel>
                          </DataTemplate>
                     </DataGridTemplateColumn.CellTemplate>
                 </DataGridTemplateColumn>
          </DataGrid.Columns>
      </DataGrid>

What I want to do is to bind the property Exercise.Objective.Descricao to the TextBlock on the Exercice.Nome

Another question, will a DataGridTemplateColumn be needed in this case?

Upvotes: 0

Views: 367

Answers (1)

Peter Hansen
Peter Hansen

Reputation: 8907

Well it will work if the Exercise class has a property called Objective, and the Objective class has a property called Descricao.

public class Exercicio
{
    public string Nome { get; set; }
    public Objective Objective { get; set; }

    public Exercicio(string nome, Objective objective)
    {
        this.Nome = nome;
        this.Objective = objective;
    }
}

public class Objective
{
    public string Descricao { get; set; }

    public Objective(string d)
    {
        this.Descricao = d;
    }
}

public MainWindow()
{
    InitializeComponent();

    var items = new ObservableCollection<Exercicio>(new[] {
        new Exercicio("Exercicio1", new Objective("Objective1")),
        new Exercicio("Exercicio2", new Objective("Objective2")),
        new Exercicio("Exercicio3", new Objective("Objective3"))
    });

    dgExercicios.ItemsSource = items;
}

And you don't need a DataGridTemplateColumn if you just want to show a string:

<!-- Works now (also in a normal text column) -->
<DataGridTextColumn Binding="{Binding Path=Objective.Descricao}" Header="Objetivo" Width="80" />

Upvotes: 1

Related Questions