按下按钮时 c# datagrid 数据不显示

c# datagrid data doesn't display when pushing button

我正在做一个 WPF (mvvm) 项目,当我按下一个按钮时尝试在数据网格中显示数据时遇到了问题。 我可以在构造函数上显示这些信息,但永远不会在软件初始化之后(例如,当我按下按钮时)

这是妈妈 xaml :

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors" 
        x:Class="noteManager.MainWindow"
        xmlns:vm="clr-namespace:noteManager.ViewModel"
        DataContext="{StaticResource noteManagerViewModel}"
        Title="NoteManager" Height="490" Width="525">
    <Grid Margin="0,0,0,-132.5">
<DataGrid Name="dataGrid1"  Grid.Row="2" Margin="8,7,-22,7" AutoGenerateColumns="False" 
                  ItemsSource="{Binding NoteGrid, Mode=TwoWay}" SelectedItem="{Binding Path=MySelectedNote}" HorizontalAlignment="Center"
                  Width="480" Grid.ColumnSpan="6" Grid.Column="1">
            <DataGrid.Columns>
                <DataGridTextColumn Width="100" Binding="{Binding Path=NoteText, Mode=TwoWay}" Header="Titre" />
                <DataGridTextColumn Width="200" Binding="{Binding Path=ContentText, Mode=TwoWay}" Header="Note" />
                <DataGridTextColumn Width="100" Binding="{Binding Path=CreatedAt, Mode=TwoWay}" Header="Date de création" />
                <DataGridTextColumn Width="100" Binding="{Binding Path=UpdatedAt, Mode=TwoWay}" Header="Dat MAJ" />
            </DataGrid.Columns>
        </DataGrid>
</Grid>
</Window>

(仅重要部分)

这是我的视图模型和类:

class DataRepository : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        void Notify(string property)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
        public IEnumerable<Note> GetNotes()
        {
            var __list = new List<Note>();
            __list.Add(new Note() { NoteText = "a", ContentText = "super texte de malade", CreatedAt = "super texte de malade", UpdatedAt = "super texte de malade", UserId = 2 });
            __list.Add(new Note() { NoteText = "b", ContentText = "super texte de malade", CreatedAt = "super texte de malade", UpdatedAt = "super texte de malade", UserId = 2 });
            __list.Add(new Note() { NoteText = "c", ContentText = "super texte de malade", CreatedAt = "super texte de malade", UpdatedAt = "super texte de malade", UserId = 2 });
            __list.Add(new Note() { NoteText = "d", ContentText = "super texte de malade", CreatedAt = "super texte de malade", UpdatedAt = "super texte de malade", UserId = 2 });
            __list.Add(new Note() { NoteText = "e", ContentText = "super texte de malade", CreatedAt = "super texte de malade", UpdatedAt = "super texte de malade", UserId = 2 });
            __list.Add(new Note() { NoteText = "f", ContentText = "super texte de malade", CreatedAt = "super texte de malade", UpdatedAt = "super texte de malade", UserId = 2 });
            return __list;
        }
    }

public class Note : INotifyPropertyChanged
    {
        public int Id { get; set; }
        public string NoteText { get; set; }
        public string ContentText { get; set; }
        public string CreatedAt { get; set; }
        public string UpdatedAt { get; set; }
        public int UserId { get; set; }

        //public virtual User User { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public void Notify(string property)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }

public class noteManagerViewModel : INotifyPropertyChanged
{

    int currentUser;
    string login;
    public string Login
    {
        get
        {
            return login;
        }
        set
        {
            login = value; Notify("Login");
        }
    }

    string titre;
    public string Titre
    {
        get
        {
            return titre;
        }
        set
        {
            titre = value; Notify("Titre");
        }
    }

    string note;
    public string Note
    {
        get
        {
            return note;
        }
        set
        {
            note = value; Notify("Note");
        }
    }
    private bool _canExecute;

    private ICommand _testConnexion;
    public ICommand testConnexion
    {
        get
        {
            return _testConnexion ?? (_testConnexion = new CommandHandler(() => Connexion(), _canExecute));
        }
    }

    private ICommand _addNote;
    public ICommand addNote
    {
        get
        {
            return _addNote ?? (_addNote = new CommandHandler(() => ajouterNote(), _canExecute));
        }
    }

    private ICommand _addUser;
    public ICommand addUser
    {
        get
        {
            return _addUser ?? (_addUser = new CommandHandler(() => AjoutUser(), _canExecute));
        }
    }

    public IEnumerable<Note> NoteGrid { get; private set; }

    public noteManagerViewModel()
    {
        _canExecute = true;
        currentUser = 0;
        var __listNote = new DataRepository();
        NoteGrid = __listNote.GetNotes();       
    }

    public event PropertyChangedEventHandler PropertyChanged;

    void Notify(string property)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }

   /// public ObservableCollection<Note> DataGridNotes { get; set; }
    void Connexion()
    {

        string cs = @"server=localhost;userid=root;
        password=root;database=notemanager";

        MySqlConnection conn = null;
        MySqlDataReader rdr = null;

        try
        {
            conn = new MySqlConnection(cs);
            conn.Open();

            string stm = "SELECT * FROM user";
            MySqlCommand cmd = new MySqlCommand(stm, conn);
            rdr = cmd.ExecuteReader();
            if (!utilisateurExistant())
            {
                MessageBox.Show("L'utilisateur n'existe pas");
            }
            else
            {
                while (rdr.Read())
                {
                    if (rdr.GetString(1) == login)
                    {
                        currentUser = int.Parse(rdr.GetString(0));
                        afficherNotes(currentUser);
                    }
                }
            }
            //sa récup toutes les notes c'est génial
            //MessageBox.Show("c'est gagné");
        }
        catch (MySql.Data.MySqlClient.MySqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            if (rdr != null)
            {
                rdr.Close();
            }

            if (conn != null)
            {
                conn.Close();
            }

        }
    }

和视图模型的构造函数:

public noteManagerViewModel()
        {
            _canExecute = true;
            currentUser = 0;
            var __listNote = new DataRepository();
            NoteGrid = __listNote.GetNotes();       
        }

当我使用此方法时,我的数据网格可以很好地显示,但是当我尝试在按下按钮而不是在构造函数中显示数据时,没有显示任何数据。

提前致谢。

让我们试试

private IEnumerable<Note> _noteGrid
public IEnumerable<Note> NoteGrid 
{
    get { return _noteGrid; } 
    private set { _noteGrid = value; Notify("NoteGrid "); }
}

您将网格绑定到 NoteGrid 属性,但不支持 INotifyPropertyChanged

按下按钮时,您可能会执行以下两项操作之一:

  1. 创建一个 new 列表,在这种情况下,您需要确保 NoteGrid 在其 setter[=25= 中引发 PropertyChanged ]
  2. 添加到 现有 列表,不会传播到 UI 和 List。要传播这些更改,您需要一个实现 INotifyCollectionChanged 的集合。 ObservableCollection<T> 是一个不错的选择,所以我会用它代替 List 作为 NoteGrid 属性.

如果您使用 List,您需要通知 UI 您想要在数据网格中显示的每个属性。

private string _notetext;
public string NoteText
{
      get
      {
         return  _notetext;
      }
      set
      {
          if(_notetext!=value)
          {
             _notetext=value;
             Notify("NoteText");
          }
      }
}