它会是这样的:
使用一个简单的模型:
public class Employee
{
public string FirstName { get; set; }
public int Age { get; set; }
}
一个依赖对象来清除它的属性
public class EmployeesDataGrid : DataGrid
{
public static readonly DependencyProperty EmployeesProperty =
DependencyProperty.Register("Employees", typeof(ObservableCollection<Employee>), typeof(EmployeesDataGrid), new PropertyMetadata(new ObservableCollection<Employee>()));
public ObservableCollection<Employee> Employees
{
get { return (ObservableCollection<Employee>)GetValue(EmployeesProperty); }
set { SetValue(EmployeesProperty, value); }
}
}
在 xaml 中使用它:
<local:EmployeesDataGrid x:Name="myGrid"/>
我将它填写在代码隐藏中(只是为了简单起见!),如下所示:
myGrid.Employees = new ObservableCollection<Employee>
{
new Employee { Age = 20, FirstName = "John"},
new Employee { Age = 30, FirstName = "Alex"}
};
在清除方法中:
foreach (FieldInfo field in depedencyObjectType.GetFields(BindingFlags.Static | BindingFlags.Public))
{
if (field.FieldType == typeof (DependencyProperty))
{
var dp = field.GetValue(depedencyObject) as DependencyProperty;
depedencyObject.ClearValue(dp);
}
}
depedencyObject
是myGrid
depedencyObjectType
是depedencyObject.GetType()
如果您将使用调试器来查看它显示的Employees
属性。myGrid
Count = 0