WPF DataGrid从ComboBox SelectionChanged传递值

时间:2013-06-02 06:02:04

标签: wpf datagrid combobox

我有一个DataGrid,它填充了一个表的值和一个TemplateColumn,它包含一个从ObservableCollection(不同的表)填充的ComboBox。这肯定不是最优雅的方式,但由于我没有时间从零开始并开始使用MVVM方法......

让我们说: 桌狗 &安培; 表Dog_breeds

网格保存表Dogs和ComboBox Dog_breeds

中的值

当在ComboBox中更改Selection时,我需要更改Dogs表中的id_dog_breed:

private void breed_combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    ComboBox comboBox = (ComboBox) sender;
    string test = comboBox.SelectedValue.ToString();
   //parse the value as int and somehow pass to the according row

  }

我怎样才能做到这一点?我相信这里肯定会有类似的问题在很久以前就得到了解答,但我找不到它。

1 个答案:

答案 0 :(得分:0)

不要将它强制转换为字符串,将组合框中的选定项目转换为ItemSource绑定的对象类型,然后你应该得到它的所有属性

private void breed_combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   ComboBox comboBox = (ComboBox) sender;
   var selectedBreed = (Dog_breed)comboBox.SelectedValue;
   //now you can access the id and pass it on 
   //assuming that the Id is property-> selectedBreed.Id
   //you should be able to access Dogs through items, I am guessing here what you structure is
   var dogs =(IEnumerable<Dog>)dataGrid.Items
   //don't know how you match them up from your question, but you should be able to find a dog
   match = dogs.FirstOrDefault(d => d.BreedName == selectedBreed.Name);
   If(match != null)
      //do your update
相关问题