質問

I have 2 tables:

Person:
    p_id  
    p_name  
    c_id  
Car:  
    c_id  
    c_name  

Here is my XAML tag:

<DataGrid Name="dataGrid1" 
          ItemsSource="{Binding Path=myPath}" 
          AutoGenerateColumns="True" />

And here is the C#:

a = new SqlDataAdapter("SELECT p.p_name AS Person, c.c_name AS Car FROM Person AS p, Car AS c WHERE p.c_id = c.c_id", c);
d = new DataSet();
a.Fill(d, "myPath");
dataGrid.DataContext = d;

Sure I can view but I cannot edit the data. I hope by some "Magic" I can turn the Car-TextColumn into a ComboBox with the Item list from the Car table.

Sorry if this question was asked, this is the first time I am trying C# and WPF, not sure what keywords to search!

役に立ちましたか?

解決

Seems like you need to use DataTemplates for this. You can hook AutoGeneratingColumn and provide there your logic. Also you may have to load Cars separatly to show them in ComboBox because might not be loaded all possible cars after executing your query.
And I strongly recommend to take a look into MVVM pattern.


There are couple similar questions that might help you with this:

他のヒント

You can handle the AutoGeneratingColumn event and add a DataGridComboBoxColumn like this -

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
  if (e.PropertyName == "CustomerID")
  {
    DataGridComboBoxColumn column = new DataGridComboBoxColumn();

    column.DataFieldBinding = new Binding("CustomerID");

    column.DataFieldTarget = ComboBoxDataFieldTarget.SelectedValue;

    column.ItemsSource = DBAccess.GetCustomers().Tables["Customers"].DefaultView;

    column.EditingElementStyle = (Style)this.RootGrid.FindResource("CustomerFKStyle");

    e.Column = column;
  }
}

refer this article for details and sample - WPF DataGrid: Working with DataGridComboBoxColumn CTP

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top