如何在WPF中使用MVVM从数据库将DataGrid绑定到数据表?

时间:2019-01-16 05:54:12

标签: wpf mvvm datagrid

我的模型,视图模型和XAML如下:

这是我的ViewModelClass:

class AllResultsViewModel
{

    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(param => this.MyAction(_cvm),
                param => this._canExecute));
        }
    }
    private bool _canExecute;
    private ComboBoxViewModel _cvm;
    public DataTable AllResults { get; set; }
    public AllResultsViewModel(ComboBoxViewModel CVM)
    {
        _canExecute = true;
        _cvm = CVM;
    }

    public void MyAction(ComboBoxViewModel cvm)
    {
       //Connecting to DB to retrieve data in datatable
    }
}
public class CommandHandler : ICommand
{
    private Action<object> _execute;
    // private bool _canExecute;
    private Predicate<object> _canExecute;

    #region Constructors

    /// <summary>
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public CommandHandler(Action<object> execute)
    : this(execute, null)
    {
    }

    /// <summary>
    /// Creates a new command.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public CommandHandler(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion // Constructors

    [DebuggerStepThrough]
    public bool CanExecute(object parameters)
    {
        //  return _canExecute;
        return _canExecute == null ? true : _canExecute(parameters);
    }

    //  public event EventHandler CanExecuteChanged;

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameters)
    {
        _execute(parameters);
    }

}

我的XAML如下:

                <DataGrid Name="results_grid" IsReadOnly="True" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Margin="10" ItemsSource="{Binding AllResults}" DisplayMemberPath="AllResultsGrid" ColumnWidth="100" RowHeight="30">

我的模型课程:

公共类AllResultsModel     {         私有DataTable _allresultsgrid;

    public DataTable AllResultsGrid
    {
        get { return _allresultsgrid; }
        set { _allresultsgrid = value; }
    }

}

我在这里错过了什么吗?代码已成功构建,并且从DB中检索了数据。但是我无法在Datagrid中查看它。

2 个答案:

答案 0 :(得分:0)

我看起来您好像缺少propertychanged()调用。 我很确定数据表不会触发任何属性更改事件。 数据加载完成后,尝试在“ AllResults”属性上调用propertychanged。

答案 1 :(得分:0)

您的代码非常混乱,我想您需要学习如何使用MVVM:https://www.tutorialspoint.com/mvvm/(下载PDF)。

在Model.cs中,您只需要定义定义对象的类,如下所示:

public class MyData
{
  public int Par1{ get; set; }
  public string Par2 { get; set; }
  public string Par3 { get; set; }
}

然后,您需要在ViewModel中创建一个可观察到的集合,以实现NotifiyPropertyChanged:

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private ObservableCollection<MyData> myData = ObservableCollection<MyData>;
    public ObservableCollection<MyData>  MyData
    {
        get { return myData; }
        set { myData = value; NotifyPropertyChanged("MyData"); }
    }
}

然后在ViewModel中,您将像这样执行MyAction()函数:

public void MyAction(ComboBoxViewModel cvm)
{
   //Connecting to DB to retrieve data in datatable
   MyData = new ObservableCollection<MyData>(dataFromDB);
}

最后,您只需将MyData绑定到xaml的ItemsSource中即可。

  

请记住要为您的视图模型分配页面/窗口数据上下文!