0

我有两个对象练习和目标,每个练习都有一个目标。在后面的代码中,我设置了练习 DataGrid 的 ItemsSource

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

在我的 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>

我想要做的是将属性Exercice.Objective.Descricao 绑定到Exercice.Nome 上的TextBlock

另一个问题,在这种情况下是否需要 DataGridTemplateColumn ?

4

1 回答 1

1

如果Exercise 类有一个名为Objective 的属性,并且Objective 类有一个名为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;
}

如果您只想显示一个字符串,则不需要 DataGridTemplateColumn:

<!-- Works now (also in a normal text column) -->
<DataGridTextColumn Binding="{Binding Path=Objective.Descricao}" Header="Objetivo" Width="80" />
于 2012-10-27T20:22:39.607 回答