具有自定义附加属性的 SortDescription

Kri*_*son 5 wpf attached-properties

在 Xaml 中,我可以使用 local:TestClass.TestProperty="1" 设置自定义附加属性

我可以使用 {Binding Path=(Namespace:[OwnerType].[PropertyName])} {Binding Path=(local:TestClass.TestProperty)} 绑定到自定义附加属性

但是,当我需要在 SortDescription 中使用自定义附加属性时,如何指定命名空间?我可以使用 new SortDescription("(Grid.Row)", ListSortDirection.Descending) 绑定到附加属性,但在这里我无法在任何地方设置命名空间......

最好的问候,杰斯珀

Ray*_*rns 2

你不能,出于同样的原因,{Binding Path=a:b.c}有效但{Binding a:b.c}无效:PropertyPath 构造函数没有命名空间上下文。

不幸的是,对于 SortDescription 来说,您无能为力。您必须找到一种不使用附加属性的排序方法。

通常我告诉人们,使用 Tag 是错误编码的一个指标,但在这种情况下,Tag 可能是您的最佳选择:您可以在 Tag 中创建一个对象,该对象具有返回您想要的实际附加属性的属性。

在 PropertyChangedCallback 中,将 Tag 实例化为内部类的实例:

public class TestClass : DependencyObject
{
  ... TestProperty declaration ...
  PropertyChangedCallback = (obj, e) =>
  {
    ...
    if(obj.Tag==null) obj.Tag = new PropertyProxy { Container = obj };
  });

  public class PropertyProxy
  {
    DependencyObject Container;
    public SomeType TestProperty { get { return GetTestProperty(Container); } }
  }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以在 SortDescription 中使用 Tag 的子属性:

<SortDescription PropertyName="Tag.TestProperty" />
Run Code Online (Sandbox Code Playgroud)

如果只有一个属性要排序,您可以简单地使用标签对其进行排序。

这样做的主要问题是使用 Tag 属性将与也尝试使用该 Tag 的任何其他代码发生冲突。因此,您可能想在标准库中查找一些晦涩的 DependencyProperty,这些属性甚至不适用于有问题的对象,并使用它来代替 Tag。