我有两个对象练习和目标,每个练习都有一个目标。 在后面的代码中,我设置了Exercises 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>
我想要做的是将属性Exercise.Objective.Descricao绑定到Exercice.Nome上的TextBlock
另一个问题,在这种情况下是否需要DataGridTemplateColumn?
答案 0 :(得分: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" />