title: Dynamic Row and Column Creation using WPF and MVVM
body: <p>Note: I'm using <em>MVVM Light Toolkit</em> and <em>MahApps.Metro</em>.</p>
  
  <p>I've checked the answers but it doesn't seem like any of them relate to my question.</p>
  
  <p>I have a Grid whose columns and header should be dynamically created. The number and value of columns is unknown to view, and the number of rows is unknown to view.</p>
  
  <p>Columns, rows and data in the rows represent a Database Table. All data is present in the ViewModel.</p>
  
  <p>I have an <code>ObservableCollection&lt;ServerRow&gt; ServerRows;</code> in my ViewModel.</p>
  
  <p>Server Row object is a Model that looks like this:</p>
  
  <pre><code>    public class ServerRow : ObservableObject
      {
           private ObservableCollection&lt;ServerColumn&gt; _columns;
  
           public ObservableCollection&lt;ServerColumn&gt; Columns
           {
               get { return _columns; }
               set { Set(() =&gt; Columns, ref _columns, value); }
           }
       }
  </code></pre>
  
  <p>This is a <code>ServerColumn</code> class :</p>
  
  <pre><code>    public class ServerColumn : ObservableObject
      {
           private string _name;
           private string _type;
           private string _value;
  
           public string Name
           {
               get { return _name; }
               set { Set(() =&gt; Name, ref _name, value); }
           }
  
           public string Type
           {
               get { return _type; }
               set { Set(() =&gt; Type, ref _type, value); }
           }
  
           public string Value
           {
               get { return _value; }
               set { Set(() =&gt; Value, ref _value, value); }
           }
  }
  </code></pre>
  
  <p>The Idea was to Bind DataGrid to <code>ObservableCollection&lt;ServerRow&gt; ServerRows;</code>, and then generate the Columns depending on the <code>ServerRow</code> object which has <code>ServerColumns</code> which in turn have <code>Name</code> (should be a header of the column), <code>Type</code> as the datatype of column data, and <code>Value</code> as the value which should be represented in every row/column.</p>
  
  <p>My XAML is pretty simple (because it's not complete, and of course- not working)</p>
  
  <pre><code>&lt;DataGrid AutoGenerateColumns="True" ItemsSource="{Binding ServerRows}"/&gt;
  </code></pre>
  
  <p>How do I write the XAML properly to achieve what I'm trying to do?</p>
  
  <p>This is the result, which makes sense because Grid is trying to show a collection of objects inside a single Column and calling its <code>ToString()</code> method.</p>
  
  <p><a href="https://i.stack.imgur.com/8QYt2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8QYt2.png" alt="enter image description here"></a></p>