C# 如何使用WPF将相关对象属性绑定到DataGridTemplateColumn中的TextBlock
我有两个目标练习和目标,每个练习有一个目标。 在代码隐藏中,我设置了DataGrid的ItemsSourceC# 如何使用WPF将相关对象属性绑定到DataGridTemplateColumn中的TextBlock,c#,wpf,binding,C#,Wpf,Binding,我有两个目标练习和目标,每个练习有一个目标。 在代码隐藏中,我设置了DataGrid的ItemsSource dgExercicios.ItemsSource = Repositorio<Exercicio>.GetAll(); dgExercicios.ItemsSource=Repositorio.GetAll(); 在我的XAML中 <DataGrid Name="dgExercicios" CellStyle="{StaticResource CellSt
dgExercicios.ItemsSource = Repositorio<Exercicio>.GetAll();
dgExercicios.ItemsSource=Repositorio.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.descripao绑定到Exercice.Nome上的TextBlock
另一个问题,在这种情况下是否需要DataGridTemplateColumn?如果练习类有一个名为Objective的属性,而Objective类有一个名为DescriptaO的属性,那么它将起作用
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;
}
公共类练习
{
公共字符串Nome{get;set;}
公共目标{get;set;}
公共演习(字符串名称、目标)
{
这个。Nome=Nome;
这个。客观=客观;
}
}
公共阶级目标
{
公共字符串描述符{get;set;}
公共目标(字符串d)
{
这个。描述=d;
}
}
公共主窗口()
{
初始化组件();
var项目=新的可观察集合(新[]{
新的实践(“实践1”,新的目标(“目标1”),
新的实践(“实践2”,新的目标(“目标2”),
新实践(“实践3”,新目标(“目标3”))
});
dgExercicios.ItemsSource=项目;
}
如果只想显示字符串,则不需要DataGridTemplateColumn:
<!-- Works now (also in a normal text column) -->
<DataGridTextColumn Binding="{Binding Path=Objective.Descricao}" Header="Objetivo" Width="80" />
在visual studio调试模式下,当程序运行时,“输出”窗口应包含绑定错误的错误消息。“你能把上面写的贴出来吗?”嗨,斯蒂芬·休利特。我从未想过查看输出窗口,如果事实上,这对我有很大帮助的话,我最终发现可能的问题是(事实上)EF中相关实体的加载。谢谢Peter,你的回答解决了我的问题。事实上,在第一个时刻它不起作用,但我最终面临的问题是EF加载相关实体,所以我将它标记为答案,再次感谢。