gpt4 book ai didi

添加时 C# datagrid 不更新 itemsource

转载 作者:行者123 更新时间:2023-11-30 23:00:15 24 4
gpt4 key购买 nike

当在文本框中键入并单击“添加员工”时,我希望它更新并显示到数据网格,我已经实现了 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; }
}

这是我的 View 模型

    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>

最佳答案

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

问题出在 SourceDataGrid

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

需要说明的是,它只在你执行 employeeModels = new List<EmployeeModel>() 时有效并且不会在 Employees.Add(employee) 时被调用

希望 WPF 有自己的 ObservableCollection负责处理的类型:

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

关于添加时 C# datagrid 不更新 itemsource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51695891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com