如何将自动生成的网格传输到具有单个列的网格

时间:2014-04-13 11:06:45

标签: c# wpf datagrid multiple-columns

实际上我正在使用自动生成的网格功能:

<DataGrid ItemsSource="{Binding UserDataObject}" Width="786" />

现在我想指定各个列,如

<DataGrid>
    <Column Header="ID" />
    <Column Header="Username" />
    <Column Header="Role">--Show Role As Selector--</Column>
</DataGrid>

这在WPF中如何运作?

说明:

我的UserDataObject定义为

ObservableCollection<User> mUserDataObject = new ObservableCollection<User>();

public ObservableCollection<User> UserDataObject
    {
        get
        {
            return mUserDataObject;
        }
    }

    //User user = new User("ID", "Username", "Password", "Role");

    public class User : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        // Attributes
        private int? _ID;
        private string _Username;
        private string _Password;
        private string _Role;

        // Constructors
        public User()
        {
        }

        public User(int pID, string pUsername, string pPassword, string pRole)
        {
            this.ID = pID;
            this.Username = pUsername;
            this.Password = pPassword;
            this.Role = pRole;
        }

        // Getter and Setter
        public int? ID
        {
            get { return _ID; }
            set { _ID = value; OnPropertyChanged("ID"); }
        }

        public string Username
        {
            get { return _Username; }
            set { _Username = value; OnPropertyChanged("Username"); }
        }

        public string Password
        {
            get { return _Password; }
            set { _Password = value; OnPropertyChanged("Password"); }
        }

        public string Role
        {
            get { return _Role; }
            set { _Role = value; OnPropertyChanged("Role"); }
        }

        // Create the OnPropertyChanged method to raise the event
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }

此外,如何添加一个在一个单元格中注册更改的事件侦听器?

1 个答案:

答案 0 :(得分:1)

您必须在dataGrid上将 AutoGenerateColumns 设置为 False ,并提供您自己的列列表。

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding UserDataObject}">
  <DataGrid.Columns>
    <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
    <DataGridTextColumn Header="Username" Binding="{Binding Username}"/>
    <DataGridComboBoxColumn Header="Role" ItemsSource="{Binding Role}"/>
  </DataGrid.Columns>
</DataGrid>

如果想要允许用户编辑属性,请使用DataGridTextColumn;如果希望用户仅从属性的允许值中选择值,请使用DataGridComboBoxColumn


  

如何添加一个在一个单元格中注册更改的事件侦听器?

由于你有正确的绑定,你不必担心在后面的代码中处理它。将代码移动到绑定到哪个单元格的属性设置器。

但是,如果您感兴趣,可以挂钩 CellEditEnding