【问题标题】:How to bind a DataGrid to a datatable from database using MVVM in wpf?如何在 wpf 中使用 MVVM 将 DataGrid 绑定到数据库中的数据表?
【发布时间】:2019-01-16 05:54:11
【问题描述】:

我的模型、视图模型和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 { 私有数据表_allresultsgrid;

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

}

我在这里遗漏了什么吗?代码构建成功,数据从数据库中检索。但我无法在 Datagrid 中查看它。

【问题讨论】:

    标签: wpf mvvm datagrid


    【解决方案1】:

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

    【讨论】:

    • 谢谢。在 MyAction() 下,我添加了 PropertyChanged("AllResults") 并且它起作用了。
    【解决方案2】:

    您的代码非常混乱,我认为您需要好好学习如何使用 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 中创建一个 observable 集合来实现 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);
    }
    

    最后,您只需在 xaml 中的 ItemsSource 中绑定 MyData。

    记得分配您的视图模型,如页面/窗口数据上下文!

    【讨论】:

      猜你喜欢
      • 2020-09-27
      • 2011-04-03
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 2023-04-08
      • 2011-09-26
      • 1970-01-01
      相关资源
      最近更新 更多