【问题标题】:C# datagrid is not updating itemsource when get addedC# datagrid 在添加时不更新 itemsource
【发布时间】:2018-08-05 15:55:54
【问题描述】:

当在文本框中输入并单击“添加员工”时,我希望它更新并显示到数据网格中,我已经实现了 INotifyPropertyChanged 和 RelayCommand。我错过了什么没有填充数据。提前致谢 这是我的模型

public class EmployeeModel
{
    public string Name { get; set; }
    public int Pedicure { get; set; }
    public int Tip { get; set; }
    public int Total { get; set; }
}

这是我的视图模型

    List<EmployeeModel> employeeModel = new List<EmployeeModel>() { };

    private ICommand _addEmployeeCommand;

    public ICommand AddEmployeeCommand
    {
        get
        {
            return _addEmployeeCommand ?? (_addEmployeeCommand = new RelayCommand(x => { AddNewEmployee(); }));
        }
    }

    public List<EmployeeModel> Employee
    {
        get { return employeeModel; }
        set
        {
            if(value != employeeModel)
            {
                employeeModel = value;
                OnPropertyChanged("Employee");
            }
        }
    }

    private string employeeName;
    public string EmployeeName
    {
        get { return employeeName; }
        set
        {
            if (value != employeeName)
            {
                employeeName = value;
                OnPropertyChanged("EmployeeName");
            }
        }
    }

    public void AddNewEmployee()
    {
        Employee.Add(new EmployeeModel { Name = EmployeeName });
    }

这是我的观点

        <TabItem Header="Employee">
            <StackPanel Orientation="Vertical">
                <DataGrid ItemsSource="{Binding Employee}">
                </DataGrid>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="Name: "/>
                    <TextBox Text="{Binding EmployeeName}"
                 Width="40"
                 Height="15"
                 VerticalAlignment="Top"/>
                    <Button Content="Add"
            Command="{Binding AddEmployeeCommand}"
                Height="20"
                VerticalAlignment="Top"/>
                </StackPanel>
            </StackPanel>

【问题讨论】:

  • 使用ObservableCollection&lt;EmployeeModel&gt;,它会在添加项目时通知 UI
  • 成功了...非常感谢

标签: c# wpf mvvm datagrid


【解决方案1】:

(我在这个答案中将名称 Employee 复数为 Employees 以供未来的读者阅读)

问题在于DataGridSource

请记住,OnPropertyChanged("Employees") 仅通知对 Employees 所做的更改,不对Employees 内所做的任何更改负责。

需要明确的是,它仅在您执行 employeeModels = new List&lt;EmployeeModel&gt;() 时才有效 并且Employees.Add(employee)时不会被调用

希望 WPF 有自己的 ObservableCollection 类型来解决这个问题:

    private ObservableCollection<Employee> _employees = new ObservableCollection<Employee>;
    public ObservableCollection<Employee> Employees { get { return _employees; } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    相关资源
    最近更新 更多