【问题标题】:How can i add a record to a datagrid and update it from another window?如何将记录添加到数据网格并从另一个窗口更新?
【发布时间】:2020-04-04 15:15:24
【问题描述】:

我在更新数据网格的内容时遇到问题。我想从用户填写信息的另一个窗口向数据网格添加一行。然后单击按钮时,数据网格应更新并显示添加的行。然而现在,它没有,我无法弄清楚我做错了什么。

因此,在添加帐户时,它应该使用新添加的记录更新主窗口中的数据网格。

现在,当我想从同一个窗口添加记录时,这就是我添加记录的方式(效果很好)

    public ObservableCollection<Account> ListAccountInfo { get; } = new ObservableCollection<Account>();

    public MainWindow()
    {
        InitializeComponent();
        ListAccountInfo.Add(new Account
        {
            IsSelected = true,
            qweqwe = "test123",
            qweqwe = "test123",
            qwe = "N/A",
            qwe = "N/A",
            qwe = "N/A",
            qwe = "N/A",
            qwe = "N/A",
            qwe = "N/A"
        });
    }

但是当我尝试从另一个窗口(带有表单的窗口)后面的代码中执行相同的操作时,它不会将新记录添加到列表中。

Account 类只是一堆get;放;。不包含任何其他内容(如果需要,我可以添加它..)

我希望有人可以帮助我解决这个问题。我还没有 wpf 的经验❤

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    最简单的解决方案是为两个窗口使用共享的DataContext 实例,并使用ICommand 将新的Account 项目实际添加到集合中:

    RelayCommand.cs
    实现取自Microsoft Docs: Patterns - WPF Apps With The Model-View-ViewModel Design Pattern - Relaying Command Logic

    public class RelayCommand : ICommand
    {
        #region Fields 
        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;
        #endregion // Fields 
        #region Constructors 
        public RelayCommand(Action<object> execute) : this(execute, null) { }
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            _execute = execute; _canExecute = canExecute;
        }
        #endregion // Constructors 
        #region ICommand Members 
        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        public void Execute(object parameter) { _execute(parameter); }
        #endregion // ICommand Members 
    }
    

    ViewModel.cs

    public class ViewModel : INotifyPropertyChanged
    {
      public ViewModel()
      {
        this.NewAccount = new Account();
        this.ListAccountInfo = new ObservableCollection<Account>()
        {
          new Account
          {
            IsSelected = true,
            Username = "test123",
            qweqwe = "test123",
            qwe = "N/A",
            qwe = "N/A",
            qwe = "N/A",
            qwe = "N/A",
            qwe = "N/A",
            qwe = "N/A"
          }
        };
      }
    
      public ObservableCollection<Account> ListAccountInfo { get; }
    
      private Account newAccount;
      public Account NewAccount
      {
        get => this.newAccount;
        set
        {
          this.newAccount = value;
          OnPropertyChanged();
        }
      }
    
      public ICommand AddAccountCommand 
      { 
        get => new RelayCommand(
          param => 
          {
            this.ListAccountInfo.Add(this.NewAccount);
            this.NewAccount = new Account();
          });  
      }
    
      #region Implementation of INotifyPropertyChanged
    
      public event PropertyChangedEventHandler PropertyChanged;
    
      [NotifyPropertyChangedInvocator]
      protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
      {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }
      #endregion Implementation of INotifyPropertyChanged
    
    }
    

    App.xaml

    <Application>
      <Application.Resources>
    
        <!-- Globally shared ViewModel instance -->
        <ViewModel x:Key="ViewModel" />  
      </Application.Resources>
    </Application>
    

    MainWindow.xaml

    <Window>
      <Window.DataContext>
        <StaticResource ResourceKey="ViewModel" />
      </Window.DatContext>
    
      <DataGrid ItemsSource="{Binding ListAccountInfo}" />
    </Window>
    

    DialogWindow.xaml

      <Window.DataContext>
        <StaticResource ResourceKey="ViewModel" />
      </Window.DatContext>
    
      <StackPanel>
        <TextBox Text="{Binding NewAccount.Username}" />
        <Button Content="Add" 
                Command="{Binding AddAccountCommand}" />   
      </StackPanel>
    </Window>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 2014-12-31
      • 1970-01-01
      相关资源
      最近更新 更多