如何在datagrid绑定中指定对象

时间:2012-09-30 14:19:52

标签: c# .net wpf silverlight xaml

如何在DataGrid绑定中指定对象? 我的数据网格有ItemsSource="{Binding Source=TripsCollection}"AutoGenerateColumns="False",列设置为:

<DataGrid.Columns>
     <DataGridTextColumn Header="ID" Binding="{Binding TripID}" IsReadOnly="True"></DataGridTextColumn>
     ...
</DataGrid.Columns>

但有错误:

  

System.Windows.Data错误:40:BindingExpression路径错误:'TripID'   'object'''Char'(HashCode = 7209070)'找不到属性。   BindingExpression:路径= TRIPID; DataItem ='Char'(HashCode = 7209070);   target元素是'TextBlock'(Name ='');目标属性是'文字'   (输入'String')。

如何将对象设置为Trip对象?

DataContext类:

private ObservableCollection<Trip> _tripsCollection;
    public ObservableCollection<Trip> TripsCollection
    {
        get { return _tripsCollection; }
        set { _tripsCollection = value; NotifyPropertyChanged("TripsCollection"); }
    }

旅行课程:

[Table(Name="Trips")]
public class Trip
{
    private uint _tripID;
    private string _start;
    private string _end;
    private DateTime _date;
    private double _length;
    private string _note;
    private uint _carID = 0;
    private EntityRef<Car> _Car;

    ..and properties for this fields..
}

设置DataContext

public MainWindow()
{
    InitializeComponent();
    string connString = @"Data Source=.\SQLEXPRESS; Integrated security=SSPI; Connect Timeout=30"; // User Instance=True";
    conn = new SqlConnection(connString);
    conn.Open();

    LogBookViewModel lbvm = new LogBookViewModel(conn);
    DataContext = lbvm;
}

1 个答案:

答案 0 :(得分:0)

您必须在ItemsSource中更改绑定:

ItemsSource="{Binding Source=TripsCollection}"

到此:

ItemsSource="{Binding TripsCollection}"

如果您将来遇到绑定问题,请尝试使用snoop