如何使用 PropertyDescriptor 实例作为绑定定义的一部分,而不是使用 PropertyPath?
Posted
技术标签:
【中文标题】如何使用 PropertyDescriptor 实例作为绑定定义的一部分,而不是使用 PropertyPath?【英文标题】:How to use a PropertyDescriptor instance as part of a Binding definition, rather than using PropertyPath? 【发布时间】:2015-11-02 10:19:09 【问题描述】:考虑以下过度简化的专用视图模型:
public class GridRowViewModel
public object RowData get; set;
public int RowHeight get;set;
//...
public class GridColumnViewModel
public PropertyDescriptor DataFieldDescriptor get; set;
public int ColumnWidth get; set;
//...
正如您可能已经猜到的那样,我希望视图模型能够在代码中操作类似网格的视图,同时将实际的数据类关注点分开。目标是允许我在“代理”视图模型中引入诸如行着色或多行编辑机制之类的功能,该模型将真实公开,不知道数据对象作为一个简单的属性。
在 XAML 方面,我想使用这样的列模板:
<DataTemplate>
<ContentControl>
<TextBox
Text="Binding
Source=RowData,
Path=(ext:GridCellExtensions.Column.DataFieldDescriptor)"
/>
</ContentControl>
</DataTemplate>
如您所知,我通过附加属性访问列实例。那部分有效。然而,我不知道如何告诉绑定引擎使用其声明的、随时可用的PropertyDescriptor
实例,而不是尝试解析一个新实例。事实上,我根本不知道这是否可以做到。
那么可以做到吗?如果有,怎么做?
另外请注意:为了使这篇文章尽可能简单,上面的模型被过度简化了,但它们的设计方式超出了当前问题的范围。因此,提出一种解决方法,迫使我重新考虑这种设计很可能会产生比它解决的问题更多的问题。因此,我真的在寻找 XAML 级别的解决方案。如果不存在,我会接受这个事实作为答案。
【问题讨论】:
ResolvedGridColumnInstance
是在哪里定义的?它是RowData
的属性吗?
@MikeEason 不,不是。它实际上是从扩展中解决的。我想保留它以使代码尽可能易于阅读,但我理解它是如何令人困惑的。我会编辑帖子。
只是提示:***.com/questions/6441318/custom-wpf-binding
【参考方案1】:
据我了解,您希望绑定的路径是动态的。
这可以通过使用行为绑定路径属性来实现。 例如:
<TextBlock >
<i:Interaction.Behaviors>
<behaviors:CustomBindingBehavior PropertyPath="Binding Path=HeaderPropertyBinding" IsBinding="Binding Path=HeaderIsBinding" />
</i:Interaction.Behaviors>
</TextBlock>
我认为这篇文章可以帮助到你:
Binding the path property of a binding
【讨论】:
以上是关于如何使用 PropertyDescriptor 实例作为绑定定义的一部分,而不是使用 PropertyPath?的主要内容,如果未能解决你的问题,请参考以下文章
Java重要技术(13)内省之属性描述符PropertyDescriptor
通过PropertyDescriptor反映射调用set和get方法