wpf Datagrid未使用对话框按钮命令更新

gfttwv5a  于 2023-01-10  发布在  其他
关注(0)|答案(1)|浏览(179)

总之,我正在开发一个WPF应用程序。在这个应用程序中,我使用了数据网格,它绑定到了一个Icollection客户集合。我使用的是MVVM。
我有一个按钮添加一个新的客户,显示一个对话框,通过点击它。通过该对话框我保存数据到我的SQL Server数据库。一切正常,但当对话框关闭(CloseAction();)。Datagrid没有更新。我该怎么办?当我回到任何其他菜单项并单击back on customer时,Datagrid会更新,而我在构造函数和命令执行中调用相同的函数。附上图片以供参考。任何解决方案都将受到真正的赞赏。

public CustomerViewModel()
        {            
            ShowNewCustomerWindowCommand = new ViewModelCommand(ExecuteShowNewCustomerWindowCommand);
            SearchCustomerCommand = new ViewModelCommand(ExecuteSearchCustomerCommand);
            GetData();            
        }

protected void GetData()
        {
            customer = new ObservableCollection<CustomerModel>();
            customer = customerRepository.GetByAll();
            customerCollection = CollectionViewSource.GetDefaultView(customer);
            customerCollection.Filter = FilterByName;
            customerCollection.Refresh();
            RaiseProperChanged();           
        }
private void ExecuteShowNewCustomerWindowCommand(object obj)
        {
            var addNewCustomer = new AddNewCustomer();
            addNewCustomer.ShowDialog();
        }

private void ExecuteSaveCustomerCommand(object obj)
        {
            customerModel.FirstName = FirstName;
            customerModel.LastName = LastName;
            customerModel.Contact = Contact;
            customerModel.Address = Address;
            customerRepository.Add(customerModel);
            CloseAction();
            GetData();
        }
csga3l58

csga3l581#

我只是猜测,因为您没有发布任何xaml或属性。我假设您至少有一个公共属性CustomerCollection,并且您的datagrid绑定到它。我将代码更改为以下内容:

public CustomerViewModel()
{     
   customer = new ObservableCollection<CustomerModel>(); 
   customerCollection = CollectionViewSource.GetDefaultView(customer);
   customerCollection.Filter = FilterByName;  

        ShowNewCustomerWindowCommand = new ViewModelCommand(ExecuteShowNewCustomerWindowCommand);
        SearchCustomerCommand = new ViewModelCommand(ExecuteSearchCustomerCommand);
        GetData();            
    }

public ICollectionView CustomerCollection {get; init;}

protected void GetData()
    {
        customer.Clear(); 
        customer.AddRange(customerRepository.GetByAll());
       
        customerCollection.Refresh();
     
    }
private void ExecuteShowNewCustomerWindowCommand(object obj)
    {
        var addNewCustomer = new AddNewCustomer();
        addNewCustomer.ShowDialog();
    }

private void ExecuteSaveCustomerCommand(object obj)
    {
        customerModel.FirstName = FirstName;
        customerModel.LastName = LastName;
        customerModel.Contact = Contact;
        customerModel.Address = Address;
        customerRepository.Add(customerModel);
        CloseAction();
        GetData();
    }

克萨姆勒

<DataGrid ItemsSource="{Binding CustomerCollection, Mode=OneWay}"
  • 在作用域中初始化一次可观察集合和ICollectionView
  • 使用.Clear()而不是新示例
  • 要添加customerRepository的地址范围.GetByAll()

相关问题