views:

23

answers:

1

I have a list of names that I'd like to have bound to a datagrid for editing/sorting/etc. But, I don't like how the DataGrid is displayed at all. Columns are placed in Alphabetical order when I really want a custom order (and I wish I could hide the ID column, or make that column not editable). I'm not sure how to start doing any of this...

NOTE: I removed a lot of "common" code (ex: INotifyPropertyChanged code...)

//PersonModel.cs
public class PersonModel
{
    public Int32 ID { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
}

//PersonViewModel.cs
public class PersonViewModel
{
    public PersonViewModel()
    {
        Init();
    }
    public PersonViewModel(ObservableCollection<PersonModel> persons)
    {
        Init(person);
    }
    private void Init(ObservableCollection<PersonModel> persons = null)
    {
        Persons = person ?? new ObservableCollection<PersonModel>();
    }

    public ObservableCollection<PersonModel> Persons { get; set; }
}

//PersonView.xaml
<UserControl ...

    ...

    <DataGrid ItemsSource="{Binding Persons}" />

    ...
</UserControl>
+1  A: 

Unless you tell it otherwise, the DataGrid infers columns via reflection. If you want to take control, you can:

<DataGrid ItemsSource="{Binding Persons}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
        <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/>
    </DataGrid.Columns>
</DataGrid>

HTH,
Kent

Kent Boogaart
I think you also need to set `AutoGenerateColumns=False` on the DataGrid, otherwise the DataGrid will generate the initial columns in addition to the ones you specifify
Rachel
+1 I swear, you and Dr. WPF are WPF Gods! I especially love the Converter pack you put out :)
myermian
I assure you: I'm mortal. But there's no denying Dr WPF's omniscience ;)
Kent Boogaart