2014-10-30 67 views
0

誰能告訴我,請我爲什麼不能在列公司(在這裏,公司名稱)收到預期的效果。在這裏,我曾嘗試我的源數據(類人)綁定到WPF DataGrid中。無法將數據綁定到數據網格

Surname | Name | Company 
--------------------------------------- 
Sidorov | Sasha | DataGridBind.Company 
Petrov | Misha | DataGridBind.Company 

MainWindow.xaml.cs:

namespace DataGridBind 
{ 

    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      Person person = new Person("Sasha", "Sidorov", new Company("Teremok")); 
      Person person1 = new Person("Misha", "Petrov",new Company("SubWay")); 
      ObservableCollection<Person> persons = new ObservableCollection<Person> { person, person1 }; 

      personDataGrid.ItemsSource = persons; 
     } 

    } 
} 

Person.cs:

namespace DataGridBind 
{ 
    public class Person 
    { 
     public string Name { get; set; } 
     public string Surname { get; set; } 
     public Company Company { get; set; } 

     public Person() { } 

     public Person(string _name, string _surname, Company _company) 
     { 
      Name = _name; 
      Surname = _surname; 
      Company = _company; 
     } 
    } 

    public class Company 
    { 
     public string Name {get;set;} 

     public Company() { } 

     public Company(string _name) 

     { 
      Name = _name; 
     } 
    } 

} 

的Xaml:

<Window 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:DataGridBind" x:Class="DataGridBind.MainWindow" 
     Title="MainWindow" Height="350" Width="525"> 

    <Grid > 

     <DataGrid x:Name="personDataGrid" AutoGenerateColumns="False" EnableRowVirtualization="True" Margin="10,10,138,177" RowDetailsVisibilityMode="Visible"> 

      <DataGrid.Columns> 

       <DataGridTextColumn x:Name="nameColumn" Binding="{Binding Name}" Header="Name" Width="SizeToHeader"/> 
       <DataGridTextColumn x:Name="surnameColumn" Binding="{Binding Surname}" Header="Surname" Width="SizeToHeader"/> 
       <DataGridTextColumn x:Name="companyColumn" Binding="{Binding Company}" Header="Company" Width="200"/> 
      </DataGrid.Columns> 
     </DataGrid> 
    </Grid> 
</Window> 

回答

1

因爲Company是你需要指定你想要的的Company屬性綁定到

<DataGridTextColumn Binding="{Binding Company.Name}" Header="Company" ... /> 

否則ToString()將被綁定對象上調用

+0

真!謝謝! – 2014-10-30 22:00:08

0

爲了避免這種情況,我們通常實現的ToString(A類)我們所有的域對象。