【问题标题】:Use reflection to reset all dependency properties back to their default?使用反射将所有依赖属性重置为默认值?
【发布时间】:2013-09-19 12:42:51
【问题描述】:

我知道可以使用反射来访问给定类的所有依赖项属性。但是是否可以使用反射或其他一些通用技术将所有依赖项属性设置回属性注册时给出的默认值?

示例 dp:

public static readonly DependencyProperty IdProperty = DependencyProperty.Register("Id", typeof(int?), typeof(OwnerClass), new PropertyMetadata(0));
public int? Id { get { return (int?)GetValue(IdProperty); } }

我可以遍历任何给定类中的所有此类 dps 并将它们设置回原始 PropertyMetadata 对象给定的值吗?

我的目的是尝试在一个抽象基类中为 wpf 应用程序中的所有视图模型创建一个“Clear()”方法。我想给 Clear() 默认行为,将所有可能注册的 dps 设置回注册时给出的默认值。用户可以在需要时/如果需要覆盖此行为。

【问题讨论】:

  • 请清楚地解释您这样做是为了达到什么目的...可能会有更好的方法。
  • 是的,你可以做到。虽然没有足够的信息。基本上是传递一个实例,找到属性,找到默认值,然后使用默认值调用属性的设置器。请告诉我你不想从吸气剂那里做那件事。
  • 我的目的是尝试在一个抽象基类中为 wpf 应用程序中的所有视图模型创建一个“Clear()”方法。我想给 Clear() 默认行为,将所有可能注册的 dps 设置回注册时给出的默认值。用户可以在需要时/如果需要覆盖此行为。
  • 您使用依赖属性而不是 INPC 的任何原因?
  • 这听起来可能是绿色的,但没有任何理由,除了 dp 是我在处理 wpf 时所接触到的。

标签: c# wpf dependency-properties


【解决方案1】:

这将是这样的:

使用一个简单的模型:

public class Employee
{
    public string FirstName { get; set; }

    public int Age { get; set; }
}

一个依赖对象以清除它的属性 P>

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);
     }
}

depedencyObjectmyGrid P>

depedencyObjectTypedepedencyObject.GetType() P>

如果你使用调试器来看看Employees财产上myGrid这表明Count = 0。 P>

【讨论】:

  • 有趣。这个作品真的很好,除了我观察到的集合似乎并没有受到影响。这表明,它调用ClearValue,但它一直在集合中的元素。我有PropertyMetadata一套新PropertyMetadata(新的ObservableCollection ()),所以我认为这将重置。 SPAN>
  • @ PriceJones这是奇怪的,它似乎工作对我很好......扶住我会更新我的代码示例答案 SPAN>
  • 我继续检查这是即使对我而言某种原因,我不能让观察集合工作答案。否则,虽然它正是我需要的。谢谢。
  • @ PriceJones是你能够让我的代码的运行?更新您的收藏的全部代码的问题,所以我们可以比较一下,看的差异 SPAN>
猜你喜欢
  • 1970-01-01
  • 2011-08-19
  • 2011-12-01
  • 2015-10-17
  • 1970-01-01
  • 2019-07-26
  • 1970-01-01
  • 2013-01-05
相关资源
最近更新 更多