DeveloperLV
DeveloperLV

Reputation: 1781

How to Bind Datagrid using MVVM Pattern?

Goal:

I am currently aiming to connect the Datagrid and the ViewModel. The ViewModel currently has code that gets data from MySQL.

Not sure where to go from here or if I am doing it correctly...

Technical_Fsqm.xaml

<Grid>
    <TextBlock Text="FSQM"/>
    <DataGrid x:Name="FSQMData"
              AutoGenerateColumns="True"
              ItemsSource="{Binding data}" Margin="0,106,0,0"/>
</Grid>

Technical_Fsqm.xaml.cs

public partial class Technical_Fsqm : UserControl
{
    public Technical_Fsqm()
    {
        InitializeComponent();
        this.DataContext = new Technical_FsqmVM();
    }
}

Technical_FsqmVM.cs

using Dapper;

public class Technical_FsqmVM : INotifyPropertyChanged
{

    public List<FsqmModel> data()
    {
        string query = "select * from table;";

        using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString))
        {
            var output = conn.Query<FsqmModel>(query).ToList();

            return output;
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Model

public class FsqmModel
{
    public int Id { get; set; }
    public string DocumentTitle { get; set; }

}

Upvotes: 1

Views: 59

Answers (1)

ASh
ASh

Reputation: 35646

is is not possible to create binding with method, only with property:

public partial class Technical_Fsqm : UserControl
{
    public Technical_Fsqm()
    {
        InitializeComponent();
        var vm = new Technical_FsqmVM();
        vm.LoadData();
        this.DataContext = vm;
    }
}

vm

public List<FsqmModel> data { get; private set; }

public void LoadData();
{
    string query = "select * from table;";

    using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString))
    {
        data = conn.Query<FsqmModel>(query).ToList();
    }
}

Upvotes: 1

Related Questions