将DataGrid绑定到WPF中的ObservableCollection <t>

时间:2016-09-30 08:59:44

标签: c# wpf data-binding datagrid datacontext

如何将Datagrid与两列(DataGridTextColumnDataGridComboBoxColumn)绑定到ObservableCollection<Team> Teams

DataGridTextColumn绑定正确。但DataGridComboBoxColumn中没有显示任何内容。

代码隐藏

   public class Team
   {
      public string Name { get; set; }
      public List<string> Members { get; set; }
   }

   public class ViewModel : INotifyPropertyChanged
   {
      public event PropertyChangedEventHandler PropertyChanged;

      private ObservableCollection<Team> teams = new ObservableCollection<Team>
      {
         new Team()
         {
            Name = "A", Members = new List<string> {"John", "Jack"},
         },
         new Team()
         {
            Name = "B", Members = new List<string> {"Sarah", "Anna"},
         }
      };
      public ObservableCollection<Team> Teams
      {
         get { return teams; }
         set
         {
            teams = value;
            RaisePropertyChanged("Teams");
         }
      }

      private void RaisePropertyChanged(string propertyName)
      {
         var handler = PropertyChanged;
         if (handler == null) return;

         handler(this, new PropertyChangedEventArgs(propertyName));
      }
   }

XAML

<DataGrid ItemsSource="{Binding Path=Teams}"
          AutoGenerateColumns="False">
    <DataGrid.Columns>

        <DataGridTextColumn Header="Team" 
                                    IsReadOnly="True"
                                    Width="*"
                                    Binding="{Binding Name}"/>

        <DataGridComboBoxColumn Header="Members" 
                                        Width="*"
                                        />

    </DataGrid.Columns>
</DataGrid>

2 个答案:

答案 0 :(得分:2)

您需要使用ViewModel实例设置控件的save属性。比如,在控制构造函数中

DataContext

并在XAML中填写DisplayMemberPath

this.DataContext = new ViewModel();

<强>更新

我是不正确的。因为<DataGridTextColumn Header="Team" DisplayMemberPath="Name" ... 不会继承DataContext,所以要按照以下方式执行操作:

DataGridComboboxColumn

答案 1 :(得分:1)

只需使用&#34; DataGridTemplateColumn&#34;。 别忘了添加一个selectedItem成员。

            <DataGridTemplateColumn Header="Members">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate DataType="wpfApplication1:Team">
                        <ComboBox ItemsSource="{Binding Members}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>