【问题标题】:WPF DataGrid pass value from ComboBox SelectionChangedWPF DataGrid 从 ComboBox SelectionChanged 传递值
【发布时间】:2013-06-02 06:02:04
【问题描述】:

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

让我们说: 餐桌狗 & 表 Dog_breeds

网格包含来自 Dogs 表和 Dog_breeds 组合框的值

当 ComboBox 中的选择发生更改时,我需要更改 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

  }

我怎样才能做到这一点?我相信这里的某个地方一定有一个类似的问题,很久以前就已经回答过了,但我没有找到它。

【问题讨论】:

    标签: wpf datagrid combobox


    【解决方案1】:

    不要将其转换为字符串,将组合框中的选定项目转换为它的 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
    

    【讨论】:

    • 我只将它转换为字符串,这样我才能看到值,仅此而已。
    • 当您将其转换为自己的类型时,您可以看到一切 :) => 您可以根据它的类型、值等对其进行操作。
    猜你喜欢
    • 2017-07-15
    • 2011-07-24
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多