Note that there are some explanatory texts on larger screens.

plurals
  1. POUse MVVM for WPF dialog box
    text
    copied!<p>I want to use MVVM in my WPF application. I currently have a Model and a view which has DataGrid and some other controls. I created a ViewModel based on my model and don't know if I did it correctly. The view is just a simple dialog box. I want to fill the DataGrid view.</p> <p>How can I tell the DataGrid to bind with the ViewModel?</p> <p><strong>I would like to bind properties(inside viewmodel like ID and Date) to the datagrid</strong>.</p> <p><strong>SO like if there is two objects inside the list I would like to see two rows in datagrid with the specific ID's and Date's.</strong></p> <p>Im setting the datacontext inside the class instead xaml.</p> <p>Here is the code so far:</p> <pre class="lang-cs prettyprint-override"><code>public class ViewModel : INotifyPropertyChanged { private string _id; private DateTime _date; private ObservableCollection&lt;Object&gt; _list; public string Id { get { return _id; } set { _id = value; PropertChanged("Id"); } } public DateTime Date { get { return _date; } set { _date = value; PropertChanged("Date"); } } public ObservableCollection&lt;Object&gt; list { get { return _list; } set { _list = value; PropertChanged("list"); } } public LicenseViewModel() { list = GetList(); } public event PropertyChangedEventHandler PropertyChanged; public void PropertChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } </code></pre> <p>And the XAML:</p> <pre><code>&lt;Window x:Class="Import" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:Controls="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" mc:Ignorable="d" ResizeMode="CanResizeWithGrip" x:Name="ImportLicense" d:DesignHeight="493" d:DesignWidth="559" Title="Import Licenses" SizeToContent="WidthAndHeight"&gt; &lt;Grid Width="538"&gt; &lt;DataGrid x:Name="Imported" VerticalAlignment="Top" AutoGenerateColumns="False" CanUserResizeColumns="True"&gt; &lt;DataGrid.Columns&gt; &lt;DataGridTextColumn Header="Entitlement ID" Binding="{Binding Path=ID}"/&gt; &lt;DataGridTextColumn Header="Date Sold" Binding="{Binding Path=Date}"/&gt; &lt;/DataGrid.Columns&gt; &lt;/DataGrid&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload