2012-10-27 98 views
0

我有两个对象Exercise和Objective,每个Exercise都有一个Objective。 在后面的代码我设置在我的XAML中练习的DataGrid如何使用WPF将相关对象属性绑定到DataGridTemplateColumn中的TextBlock

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

和的ItemsSource。

<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到TextBlock绑定的Exercice.Nome

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

+1

在Visual Studio调试模式下,你的程序运行时,在“输出”窗口应包含错误消息用于绑定错误。你可以发表它说什么? –

+0

@Hi Stephen Hewlett。我从来没有想过要看看输出窗口,如果事实上,它帮助了我很多,我最终发现可能的问题是(事实上)在EF中加载相关实体。 – Ewerton

回答

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" /> 
+0

感谢彼得,你的回答解决了我的问题。事实上,在第一时间它不起作用,但我最终面临,我的问题是与EF加载相关entites,所以我将它标记为答案,再次感谢。 – Ewerton

相关问题