Search code examples
c#wpfdata-bindingwpfdatagridobservablecollection

is it possible to bind a datagrid to a object


I would like to bind a DataGrid to an object, and not to a collection of objects,

My scenario is,

I have a single record with a few columns in the database that the user will keep updating,
and for UI design purposes we would like the user to update it through a DataGrid with a single row. As a work around, I created an ObserverbaleCollection and added that record, but I would like to do it the right way so please if someone could guide me.

Thanks

p.s. as requested Below

here his the xaml for the datagrid i tried

<DataGrid CanUserAddRows="False" IsReadOnly="False" AutoGenerateColumns="False" ItemsSource="{Binding FacilityDefaults}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Price " Binding="{Binding Price,UpdateSourceTrigger=LostFocus}"/>
        <DataGridTextColumn Header="Default Temperature" Binding="{Binding DefaultTemperature,UpdateSourceTrigger=LostFocus}"/>
    </DataGrid.Columns>
</DataGrid>`

Solution

  • Using a Datagrid as an edit mechanism for a single record seems like the wrong choice in the first place. A Datagrid is made to work with a collection of items not really a single item. But if you insist on using it in this manner, then binding to a collection with just your one record in it is the simplest way to make it work. A DataGrid's ItemsSource expects an IEnumerable (MSDN), so binding it to a single object would be awkward to say the least.