Mrg Gek
Mrg Gek

Reputation: 936

What is the best approach to populate DataGrid with static data in WPF MVVM?

By static data I mean data which will be changed very rarely. In my case I need to make a table in which first two columns will be read only and represent Name and Code for each Row. Row records of this two columns must be displayed regardless of whether there is dynamic data.

-----------------------------------------------------------
   Column1   |  Column 2  |   Column 3   |  ..............|
-----------------------------------------------------------
Static Data  |Static Data | Dynamic Data |  Dynamic Data  |
-----------------------------------------------------------

What is the best approach to populate DataGrid with static data in WPF MVVM? Through XAML or define Enumm, or store it in database, or there is some other way? Dynamic data will be loaded from database if there is any records.

Upvotes: 0

Views: 761

Answers (1)

mm8
mm8

Reputation: 169218

The best approach would be to set or bind the ItemsSource property of the DataGrid to an IEnumerable where the type T has a public read-only property for each "static" data column:

    public class Item
    {
        public string StaticColumnA { get; } = "Some static value";
        public string StaticColumnB { get; } = "Some static value";
        public string DynamicColumnA { get; set; }
    }

    public MainWindow()
    {
        InitializeComponent();

        List<Item> theItems = new List<Item>() { };
        dg.ItemsSource = theItems;
    }

    <DataGrid x:Name="dg" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding StaticColumnA}" IsReadOnly="True" />
            <DataGridTextColumn Binding="{Binding StaticColumnB}" IsReadOnly="True" />
            <DataGridTextColumn Binding="{Binding DynamicColumnA}" />
        </DataGrid.Columns>
    </DataGrid>

The data object should return the static values, which may be strings, enumeration values or whatever, through public properties.

Upvotes: 1

Related Questions