gpt4 book ai didi

c# - 想要将 Cs 文件中的 List 绑定(bind)到 Xaml 中的 Grid,而无需隐藏代码中的任何代码

转载 作者:太空宇宙 更新时间:2023-11-03 16:50:00 25 4
gpt4 key购买 nike

我想将 Xaml 文件中的 DataGrid 与不在代码隐藏中但在 cs 文件中的集合绑定(bind)

我尝试了不同的方法但没有成功,其实我不想在代码隐藏文件中编写任何代码。

类代码

public class Employee : INotifyPropertyChanged
{
private int _Id;
private string _FirstName;
private string _LastName;
private double _Salary;
public event PropertyChangedEventHandler PropertyChanged;

public Employee()
{
}
public Employee(int pId, string pFirstName, string pLastName, double pSalary)
{
Id = pId;
FirstName = pFirstName;
LastName = pLastName;
Salary = pSalary;
}

public int Id
{
set
{
_Id = value;
NotifyPropertyChanged("Id");
}
get { return _Id; }
}
public string FirstName
{
set
{
_FirstName = value;
NotifyPropertyChanged("FirstName");
}
get { return _FirstName; }
}
public string LastName
{
set
{
_LastName = value;
NotifyPropertyChanged("LastName");
}
get { return _LastName; }
}
public double Salary
{
set
{
_Salary = value;
NotifyPropertyChanged("Salary");
}
get { return _Salary; }
}
private void NotifyPropertyChanged(string pProperty)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(pProperty));
}
}


public class EmployeeCollection
{
ObservableCollection<Employee> lstEmp = new ObservableCollection<Employee>();
public ObservableCollection<Employee> GetEmployees()
{
lstEmp.Add(new Employee(1,"Firstname 1", "Lastname 1", 1.1 ));
lstEmp.Add(new Employee(2, "Firstname 2", "Lastname 2", 2.2));
lstEmp.Add(new Employee(3, "Firstname 3", "Lastname 3", 3.3));
lstEmp.Add(new Employee(4, "Firstname 4", "Lastname 4", 4.4));
lstEmp.Add(new Employee(5, "Firstname 5", "Lastname 5", 5.5));
lstEmp.Add(new Employee(6, "Firstname 6", "Lastname 6", 6.6));

return lstEmp;
}
}

它的 Xaml 代码

<my:DataGrid  AutoGenerateColumns="true" Margin="20,0,68,10" Name="dataGrid2" Height="135" VerticalAlignment="Bottom" />

最佳答案

如果我能以对我有意义的方式修改类,我会更改 GetEmployees()到静态属性。然后您可以简单地编写( local 是包含 Employee 的命名空间的命名空间前缀):

<DataGrid ItemsSource="{x:Static local:Employee.Employees}" />

如果你想保持类的原样,首先声明一个ObjectDataProvider作为资源(例如在 <Window.Resources> 中):

<ObjectDataProvider ObjectType="local:Employee" MethodName="GetEmployees"
x:Key="employees" />

然后使用它:

<DataGrid ItemsSource="{Binding Source={StaticResource employees}}" />

关于c# - 想要将 Cs 文件中的 List 绑定(bind)到 Xaml 中的 Grid,而无需隐藏代码中的任何代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4295522/

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